Increment the counter by 1 for each unique group of values.

I want to create an ever-increasing counter for each group, where each group is a unique combination of person and day.

Here's what the data looks like:

> df
  person      date
1      0    monday
2      0   tuesday
3      1    monday
4      1    monday
5      1   tuesday
6      2    monday
7      2    monday
8      2   tuesday
9      2 wednesday

So I want to add a new variable starting with 1, and adds for each new combination of person and day.

> df
  person      date counter
1      0    monday       1
2      0   tuesday       2
3      1    monday       3
4      1    monday       3
5      1   tuesday       4
6      2    monday       5
7      2    monday       5
8      2   tuesday       6
9      2 wednesday       7

I hope the data is clear enough. The counter continues until it reaches the end of the data set.

+4
source share
2 answers

You can use rleidfrom devel version data.table. Installation instructions for the devel version:here

 library(data.table)#v.9.5+
 setDT(df)[, counter:= rleid(date)][]
 #    person      date counter
 # 1:      0    monday       1
 # 2:      0   tuesday       2
 # 3:      1    monday       3
 # 4:      1    monday       3
 # 5:      1   tuesday       4
 # 6:      2    monday       5
 # 7:      2    monday       5
 # 8:      2   tuesday       6
 # 9:      2 wednesday       7

or

library(dplyr)
df %>%  
   mutate(counter= cumsum(date!=lag(date, default=FALSE)))
+4
source

Basic package:

df1 <- data.frame(unique(df), counter= 1:nrow(unique(df)))
merge(df, df1)

Conclusion:

  person      date counter
1      0    monday       1
2      0   tuesday       2
3      1    monday       3
4      1    monday       3
5      1   tuesday       4
6      2    monday       5
7      2    monday       5
8      2   tuesday       6
9      2 wednesday       7
+2
source

Source: https://habr.com/ru/post/1599169/


All Articles