I'm looking to replace the NA values in this example data frame with either 'A' or 'B' depending on their 'second' column category: (A for A1, B for B1)
df <- data.frame(first = c("A","A",NA,NA,"B",NA,NA,NA),second = c(rep("A1",4),rep("B1",4)))
df
first second
1 A A1
2 A A1
3 <NA> A1
4 <NA> A1
5 B B1
6 <NA> B1
7 <NA> B1
8 <NA> B1
This is what I would like the resulting data frame to look like:
first second
1 A A1
2 A A1
3 A A1
4 A A1
5 B B1
6 B B1
7 B B1
8 B B1
I tried this solution but obviously it didn't work:
df$first[is.na(df$first)] <- unique(df[!is.na(df$first),"first"])
I have a feeling there might be a dplyr solution but cannot think of it.
Thank you!