0

This turns out to be pretty easy for some of you: theoretically is about using the group_by() function and the filter() function. However to me is still problematic

library(dplyr)

df <- data.frame(Serial=c(1010,1010,1102,1102,1102,1103), Value=c(1,2,1,2,3,1))
df

 Serial Value
1   1010     1
2   1010     2
3   1102     1
4   1102     2
5   1102     3
6   1103     1

I would like to create an id variable based on serial number and Value such as

Serial    Value  Id
1   1010     1     1
2   1010     2     1
3   1102     1     2
4   1102     2     2
5   1102     3     2
6   1103     1     3

Any help is welcomed

user11418708
  • 902
  • 4
  • 10

1 Answers1

0

An option would be

df$Id <- cumsum(df$Value == 1)
df$Id
#[1] 1 1 2 2 2 3

Or with factor

as.integer(factor(df$Serial))

Or using match

with(df, match(Serial, unique(Serial))
akrun
  • 874,273
  • 37
  • 540
  • 662