0

I got a df such a this

structure(list(id = c(1162, 1162, 1162, 1388, 1388, 1388, 1492, 
1492, 1492), chapter = c(1, 2, 1, 3, 4, 5, 2, 1, 3)), class = "data.frame", row.names = c(NA, 
-9L))

and I want to replace the id column values with numbers to make it look like this

structure(list(id2 = c(1, 1, 1, 2, 2, 2, 3, 3, 3), chapter = c(1, 
2, 1, 3, 4, 5, 2, 1, 3)), class = "data.frame", row.names = c(NA, 
-9L))
kam
  • 345
  • 1
  • 8

2 Answers2

1

Try this:

df$id <- as.numeric(as.factor(df$id))
Tur
  • 604
  • 4
  • 9
0

cumsum the differences.

df1 <- transform(df1, id=c(1, cumsum(diff(df1$id) > 0) + 1))
df1
#   id chapter
# 1  1       1
# 2  1       2
# 3  1       1
# 4  2       3
# 5  2       4
# 6  2       5
# 7  3       2
# 8  3       1
# 9  3       3
jay.sf
  • 60,139
  • 8
  • 53
  • 110