I have a df:
ID Tag
999 YES
999
100
100 NO
500
I need to fill the 'Tag' values to the matching ID variable - so that every instance of that ID has a matching Tag So I'll end up with:
ID Tag
999 YES
999 YES
100 NO
100 NO
500
I have a df:
ID Tag
999 YES
999
100
100 NO
500
I need to fill the 'Tag' values to the matching ID variable - so that every instance of that ID has a matching Tag So I'll end up with:
ID Tag
999 YES
999 YES
100 NO
100 NO
500
You can use ave
to fill na
per group.
df$Tag <- with(df, ave(Tag, ID, FUN=function(x) {
i <- is.na(x)
x[i] <- x[!i][1]
x
}))
df
# ID Tag
#1 999 YES
#2 999 YES
#3 100 NO
#4 100 NO
#5 500 <NA>
Or using fill
library(dplyr)
library(tidyr)
df %>% group_by(ID) %>% fill(Tag, .direction = "downup")
## A tibble: 5 x 2
## Groups: ID [3]
# ID Tag
# <int> <fct>
#1 999 YES
#2 999 YES
#3 100 NO
#4 100 NO
#5 500 NA