# 有没有一种方法可以用R中的另一个数据框替换行中的数据？

``````df1 <- data.frame(x = c(1,2,3,4), y = c("a", "b", "c", "d"))

df2 <- data.frame(x = c(1,2), y = c("f", "g"))
``````

``````data.frame(x = c(1,2,3,4), y = c("f","g","c","d")
``````

``````df1[which(df1\$x %in% df2\$x),]\$y <- df2[which(df1\$x %in% df2\$x),]\$y
``````

(OoO)

A join option with `data.table` where we join `on` the 'x' column, assign the values of 'y' in second dataset (`i.y`) to the first one with `:=`

``````library(data.table)
setDT(df1)[df2, y := i.y, on = .(x)]
``````
pculpa

(I add `stringsAsFactors=FALSE` to the frames so that the merging and later work is without any issue, as `factor`s can be disruptive sometimes.)

``````df1 <- data.frame(x = c(1,2,3,4), y = c("a", "b", "c", "d"), stringsAsFactors = FALSE)
# df2 <- data.frame(x = c(1,2), y = c("f", "g"), stringsAsFactors = FALSE)
merge(df1, df2, by = "x", all = TRUE)
#   x y.x  y.y
# 1 1   a    f
# 2 2   b    g
# 3 3   c <NA>
# 4 4   d <NA>
transform(merge(df1, df2, by = "x", all = TRUE), y = ifelse(is.na(y.y), y.x, y.y))
#   x y.x  y.y y
# 1 1   a    f f
# 2 2   b    g g
# 3 3   c <NA> c
# 4 4   d <NA> d
transform(merge(df1, df2, by = "x", all = TRUE), y = ifelse(is.na(y.y), y.x, y.y), y.x = NULL, y.y = NULL)
#   x y
# 1 1 f
# 2 2 g
# 3 3 c
# 4 4 d
``````

Dplyr：

``````library(dplyr)
full_join(df1, df2, by = "x") %>%
mutate(y = coalesce(y.y, y.x)) %>%
select(-y.x, -y.y)
#   x y
# 1 1 f
# 2 2 g
# 3 3 c
# 4 4 d
``````