Reputation: 77
I've tried looking at other questions but none quite hits the mark. I am trying to compare two rows and depending on the result of the comparison add a number in a new column at the end of the row. I am using mtcars:
The code I use is simply this:
for (i in 1:nrow(mtcars)-1) {
if (mtcars[i,6] > mtcars[i+1,6] ){
mtcars[i,12] = 5
}
}
Where col 12 is a new column. I get the following error messages:
Error in if (mtcars[i, 6] < mtcars[i + 1, 6]) mtcars[i, 12] = 10 : argument is of length zero
There shouldn't be any null arguments so I have no clue what is returning a null argument and why this is an issue.
Thanks John
Upvotes: 0
Views: 1968
Reputation: 55350
Look at 1:nrow(mtcars)-1
Compare that with 1:(nrow(mtcars)-1)
# Note the parens aroud the right-hand-side of ':'
The error comes from trying to take mtcars[0, ]
which will be a zero-length vector, which in turn messes up your if
clause
> 1:nrow(mtcars)-1
[1] 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
[25] 24 25 26 27 28 29 30 31
> 1:(nrow(mtcars)-1)
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
[25] 25 26 27 28 29 30 31
Upvotes: 2