[Solved] Fill missing values by finding matches in another column


Here’s a one-liner with match:

df$TakerId = df$AltTakerId[match(df$QuestionId, df$AltQuestionId)]
df
#    QuestionId AltQuestionId AltTakerId TakerId
# 1          NA             1          7      NA
# 2          NA             2         13      NA
# 3          NA             4         10      NA
# 4          NA             5         15      NA
# 5          NA             6         17      NA
# 6           1            NA         NA       7
# 7          NA             8          8      NA
# 8          NA            10         11      NA
# 9           6            NA         NA      17
# 10          2            NA         NA      13
# 11         NA            14         25      NA
# 12          6            NA         NA      17
# 13         NA            16         29      NA
# 14          4            NA         NA      10
# 15         NA            18         35      NA
# 16         NA            20         29      NA

Using Milan’s nicely provided data:

df <- data.frame(
  QuestionId = c(rep(NA, 16)),
  AltQuestionId = c(1, 2, 4, 5, 6, NA, 8, 10, NA, NA, 14, NA, 16, NA, 18, 20),
  AltTakerId = c(7, 13, 10, 15, 17, NA, 8, 11, NA, NA, 25, NA, 29, NA, 35, 29)
)
df$QuestionId[c(6, 9, 10, 12, 14)] <- c(1, 6, 2, 6, 4)

2

solved Fill missing values by finding matches in another column