1

Suppose I have the dataset

|ID |

| 1 | | 1 | | 1 | | 1 | | 2 | | 2 | | 2 |

I want to create a new variable where I add all the rows with the same ID number. It should look like

ID New
1 4
1 4
1 4
1 4
2 3
2 3
2 3

Because I have four 1s, and three 2s.

1 Answers1

1
df %>% summarise(n = n(), .by = ID)

  ID n
1  1 4
2  2 3

# or, if you want duplicates:

df %>% mutate(n = n(), .by = ID)

  ID n
1  1 4
2  1 4
3  1 4
4  1 4
5  2 3
6  2 3
7  2 3
Mark
  • 7,785
  • 2
  • 14
  • 34