1

Apparently I am trying to subset my variable with positive and "negative indexes". However debugging the code, I can not why R studio is interpreting it as I am mixing negative and positive subsets.

Here is the part of the code:

 if (stepcount > 192 | sum(na.omit(ppt[i-193:i-1])) < 0.6) {statement}

Error:

Error in ppt[i - 193:i - 1] : 
  only 0's may be mixed with negative subscripts

Debugging the code I see that my value for i at this point is 3572 which means nor negative subsetting in ppt[i - 193:i - 1]

If it helps, just some more information: if I use two "or" operator instead of one, like:

if (stepcount > 192 || sum(na.omit(ppt[i-193:i-1])) < 0.6) {statement}

I still get the same err but in i being 3603. Honestly I don't know the difference but may be it conveys some kind of information that could clarify the problem.

I think that this is probably a simple thing that I am not aware of and that the reproducible code would not be necessary (since it is a too long code to analyse a large data. However I could post it on, if you guys think that is necessary.

Alan Alves
  • 61
  • 1
  • 2
  • 9
  • 1
    Try using `(i-193):(i-1)` – Rich Scriven Jul 08 '14 at 20:13
  • 1
    So this is a problem with operator precedence: the `:` operator has higher precedence than `-`. The expression `i-193:i-1` is the same as `i - (193:i) -1`. As the comment above states, you (seem to) want `(i-193):(i-1)`. – jlhoward Jul 08 '14 at 20:32

2 Answers2

3

I think you want:

ppt[i - 193:(i - 1)]

Otherwise, you have a -1 in the list when i > 193, and positive, negative and 0 entries when i > 194:

195 - 193:195 - 1
## [1]  1  0 -1
Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112
  • 1
    Let's say i = 195. What I wanted is the subset of ppt from index i - 193 (which is 2) to index number i - 1 (which is 194). If I do as you suggested i get something like this: `> k <- seq(from=1,to=1000,by=2) > i <- 195 > k[i - 193:(i - 1)] [1] 3 1` Doing the guy commented I get what I need. Thank you for your answer, and sorry for not expressing well at the question. – Alan Alves Jul 09 '14 at 13:52
2

As suggested by Richard Scriven and explained by jlhoward, the solution is to put the subset in parenthesis:

if (stepcount > 192 | sum(na.omit(ppt[(i-193):(i-1)])) < 0.6) {statement}

Example:

> k <- seq(from=1,to=1000,by=2)
> i <- 195
> k[(i - 193):(i - 1)]
  [1]   3   5   7   9  11  13  15  17  19  21  23  25  27  29
 [15]  31  33  35  37  39  41  43  45  47  49  51  53  55 ...
Alan Alves
  • 61
  • 1
  • 2
  • 9