Мы можем использовать match
:
#Copy cluster value
df$New_col <- df$cluster
#Get NA indices
inds <- is.na(df$New_col)
#Get corresponding cluster values for NA values.
df$New_col[inds] <- with(df, cluster[match(id[inds], to)])
df
# id cluster from to New_col
#1 A NA <NA> <NA> 5
#2 B 2 B D 2
#3 C 5 C A 5
#4 D NA <NA> <NA> 2
#5 E 5 E B 5
#6 F NA <NA> <NA> 3
#7 G 3 G F 3
данные
df <- structure(list(id = structure(1:7, .Label = c("A", "B", "C",
"D", "E", "F", "G"), class = "factor"), cluster = c(NA, 2L, 5L,
NA, 5L, NA, 3L), from = structure(c(NA, 1L, 2L, NA, 3L, NA, 4L
), .Label = c("B", "C", "E", "G"), class = "factor"), to = structure(c(NA,
3L, 1L, NA, 2L, NA, 4L), .Label = c("A", "B", "D", "F"), class = "factor")),
class = "data.frame", row.names = c(NA, -7L))