Create a variable conditioned to the values that take different rows. for example. I have a database, made up of 3 variables. (ID, COD1, COD2).
ID represents an identification code. COD1: represents the categories to which each individual belongs. COD2: represents a registry characteristic.
We want to create a variable 3: COD3 which represents how many COD1 categories the individual belongs to.
COD3 = A if the same ID have 2 categories in COD1
COD3 = B if the same ID have 3 categories in COD1
COD3 = C if the same ID have just one category in COD1
I was thinking of a code using dplyr as shown below but i dont know how to make conditios that contemplate not only the row but the whole group.
df %>% mutate(COD3 = case_when(ID == 1 & COD2 == ?? ~ A)
what I have.
| ID | COD1 | COD2 |
|---|---|---|
| 01 | 10 | 1SW |
| 01 | 11 | 232 |
| 01 | 10 | 12D |
| 02 | 10 | 13V |
| 02 | 11 | 2P0 |
| 02 | 12 | PL4 |
| 03 | 10 | 55R |
| 03 | 10 | P01 |
| 03 | 10 | MN7 |
What I want
| ID | COD1 | COD2 | COD3 |
|---|---|---|---|
| 01 | 10 | 1SW | A |
| 01 | 11 | 232 | A |
| 01 | 10 | 12D | A |
| 02 | 10 | 13V | B |
| 02 | 11 | 2P0 | B |
| 02 | 12 | PL4 | B |
| 03 | 10 | 55R | C |
| 03 | 10 | P01 | C |
| 03 | 10 | MN7 | C |
I would appreciate any help in this regard.