| code |
name |
| 123 |
A |
| 123 |
B |
| 666 |
X |
| 999 |
M |
| 999 |
M |
| 555 |
P |
| 555 |
Q |
| 555 |
R |
I want to mutate a variable wanted, which will count the number of different names for each code. For example, for code 123 the new variable will take the value 2 but for code 999 the value will be 1 since names are the same.
Here is the desired output:
| code |
name |
wanted |
| 123 |
A |
2 |
| 123 |
B |
2 |
| 666 |
X |
1 |
| 999 |
M |
1 |
| 999 |
M |
1 |
| 555 |
P |
3 |
| 555 |
Q |
3 |
| 555 |
R |
3 |
library(dplyr)
# toy data
df <- tibble(
code = c(123, 123, 666, 999, 999, 555, 555, 555),
name = c("A", "B", "X", "M", "M", "P", "Q", "R"),
wanted = c(2, 2, 1, 1, 1, 3, 3, 3)
)