Negative Index Error in R

I have the following code snippet:

if(k<=100 && k>=0 ) { j[k+seq(-50,150)]<-F; } else { j[k+seq(-100,100)]<-F; } 

And the following error:

Error in j [k + seq (-50, 150)] <-F: only 0 can be mixed with negative indices

Why do I get this, although I set conditions if the indices can run to negative values?

+4
source share
1 answer

When k = 25 , let's say your if condition if true ( k less than 100, but greater than 0). But 25 + (-50) is -25. But 25 + 150 = 175, a positive index. You cannot mix positive and negative indices with a subset.

I suppose I should add that part of the reason you cannot do this is because positive and negative indices have different meanings. x[3] means you want to select the third item, while x[-3] means you want to omit the third item. It would be weird to keep track of which indexes relate to those elements if you started dropping elements while selecting others.

+10
source

All Articles