6

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's may be mixed with negative subscripts

Why am I getting this even though I have set the conditions if the subscripts may run into the negative values?

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
Concerned_Citizen
  • 6,548
  • 18
  • 57
  • 75

1 Answers1

12

When k = 25, say, then your if condition is true (k is less than 100 but greater than 0). But 25 + (-50) is -25. But 25 + 150 = 175, a positive index. You can't mix positive and negative indices when subsetting.

I suppose I should add that part of the reason you can't do this is that positive and negative indices have different meaning. x[3] means you want to select the third element, whereas x[-3] means you want to omit the third element. It would get confusing to keep track of which indices referred to which elements if you started dropping elements at the same time you are selecting others.

joran
  • 169,992
  • 32
  • 429
  • 468
  • Great answer. I'd like to know: why did the OP start out by trying to define the indices of j in this manner? If, e.g., k were -10 to begin with, things would be even uglier. He needs to figure out what the range of k-values he expects and adjusting the index offset appropriately. – Carl Witthoft Sep 05 '11 at 13:08