1

I have a dataframe as below:

RecordID <- c("a","b","c","d","e","f","g")
row.number <- c(1,2,10,11,12,45,46)
df <- data.frame(RecordID, row.number)
df$frame.change =1

I want the value in frame.change to increase by 1 from the previous row if there is an increase in row.number of more than 1 from the previous row. I am trying the following code but it doesn't work:

for( i in 2:nrow(df)){
  df$frame.change[i] <- if( (df$frame.change[i] - df$frame.change[i-1]) <1 ){df$frame.change[i-1] }else{ df$frame.change[i-1] +1 }
  cat("-")
}

It doesn't need to be done within a for loop and I presume lapply will be the solution but I can't seem to get this to work.

Help appreciated

Jaap
  • 81,064
  • 34
  • 182
  • 193
DenJJ
  • 404
  • 4
  • 16
  • `df$frame.change <- cumsum(c(1,diff(df$row.number) > 1))` – Jaap Jan 29 '17 at 11:22
  • Perhaps a more canonical Q&A on the very useful `cumsum(diff(...` method: [How to partition a vector into groups of regular, consecutive sequences?](http://stackoverflow.com/questions/5222061/how-to-partition-a-vector-into-groups-of-regular-consecutive-sequences). – Henrik Jan 29 '17 at 16:36

1 Answers1

1

A combination of cumsum and diff is all you need:

df$frame.change <- cumsum(c(1, diff(df$row.number) > 1))

which gives:

> df
  RecordID row.number frame.change
1        a          1            1
2        b          2            1
3        c         10            2
4        d         11            2
5        e         12            2
6        f         45            3
7        g         46            3
Jaap
  • 81,064
  • 34
  • 182
  • 193