I have a dataframe as below, with all the values corresponding to an 'other' type, belonging to specific IDs:
df <- data.frame(ID = c("1", "1", "1", "2", "2", "3"), type = c("oth", "oth", "oth", "oth", "oth", "oth"), value = c("A", "B", "B", "C", "D", "D"))
ID type value
1 oth A
1 oth B
1 oth B
2 oth C
2 oth D
3 oth D
I would like to change the types of the rows with values A, B, C to be 1, 2, 3 respectively (D stays as 'oth'). If it is changed, I would like to keep the 'oth' row but have the value as NA.
The above df would result into:
df2 <- data.frame(ID = c("1", "1", "1", "1", "1", "1", "2", "2", "2", "3"), type = c("1", "oth", "2", "oth", "2", "oth", "3", "oth", "oth", "oth"), value = c("A", NA, "B", NA, "B", NA, "C", NA, "D", "D"))
ID type value
1 1 A
1 oth <NA>
1 2 B
1 oth <NA>
1 2 B
1 oth <NA>
2 3 C
2 oth <NA>
2 oth D
3 oth D
Note that any rows that match A,B,C will create a new row with correct type, but change the original one to value = NA. If possible, a dplyr solution would be preferred.
Any help would be appreciated, thanks!