2021年3月27日星期六

R: comparing a value with next value in a column

I have a data set of the following form:

Interval | Count | criteria
0 0 0
0 1 0
0 2 0
0 3 0
1 4 1
1 5 2
1 6 3
1 7 4
2 8 1
2 9 2
3 10 3

I need to compare the values in the Interval. I first need to create a new variable to store the values. If the value in the Interval is the same as the next value, then the new variable should have blanks. If the Interval value is not the same as the next value, then it should return criteria/Count. Output should be like this:

Interval | Count | criteria | N

0 0 0
0 1 0
0 2 0
0 3 0 0
1 4 1
1 5 2
1 6 3
1 7 4 0.5714
2 8 1
2 9 2 0.2222

3 10 3

Here is my code:

fid$N<-''  for (i in 1:length(fid$Interval))  {  if (fid$Interval[i] != fid$Interval[i+1])    fid$N<-fid$criteria/fid$Count   else    fid$N<-''   }  

and this is the error I am getting.

Error in if (fid$Interval[i] != fid$Interval[i + 1]) fid$N <- fid$criteria/fid$Count else fid$N <- "" : missing value where TRUE/FALSE needed

To add that, there is no missing value in the data set.

I would appreciate if anyone could help.

https://stackoverflow.com/questions/66837571/r-comparing-a-value-with-next-value-in-a-column March 28, 2021 at 09:05AM

没有评论:

发表评论