我们可以使用Map
df1[as.character(df2$Variable)] <- Map(function(x, y)
replace(x, is.na(x), y), df1[as.character(df2$Variable)], df2$Value)
如果值不是NA 而只是* 那么
df1[as.character(df2$Variable)] <- Map(function(x, y)
replace(x, x=="*", y), df1[as.character(df2$Variable)], df2$Value)
df1
# A B C D
#1 1 3 4 0
#2 4 1 5 9
#3 0 1 2 0
#4 1 2 9 4
如果数据集'df1'不是字符,那么做
df1[] <- as.matrix(df1)
数据
df1 <- structure(list(A = c(1L, 4L, 0L, 1L), B = c("3", "*", "*", "2"
), C = c("4", "5", "2", "*"), D = c("*", "9", "*", "4")), .Names = c("A",
"B", "C", "D"), class = "data.frame", row.names = c(NA, -4L))
df2 <- structure(list(Variable = c("A", "B", "C", "D"), Value = c(2L,
1L, 9L, 0L)), .Names = c("Variable", "Value"), class = "data.frame",
row.names = c(NA, -4L))