为什么这不能正确替换列? df1 [i,b]< - df2 [i,b]

时间:2017-06-09 17:11:20

标签: r

所以我有一个大型数据帧,我们称之为df1。现在,我想用另一个具有完全相同列名和id的数据帧的值替换行和列的子集。但是下面的代码并没有产生我想要的结果,我也不明白为什么。

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

df1[df2$id, names(df2)] <- df2

我看过replace,但不知道如何在两个数据框中使用它。我正在寻找像merge这样取代价值的东西。

1 个答案:

答案 0 :(得分:2)

两个数据框中有不同的因子级别。这应该适合你:

df1 <- data.frame(id = c(1:4), a = c("a", "a", "a", "a"), b = c("b", "b", "b", "b"), c = c("c", "c", "c", "c"), d = c("d", "d", "d", "d"), stringsAsFactors = FALSE)
df2 <- data.frame(id = c(2,3), b = c("x", "x"), c = c("y", "y"), stringsAsFactors = FALSE)

df1[df2$id, names(df2)] <- df2