更新表行值有条件地匹配R

时间:2017-04-21 04:26:08

标签: r merge match

我试图用df.2的值更新df.1,当列值df.1 $ time和df.1​​ $ region分别匹配df.2 $ time df.2 $ region

df.1

region, time, value
a, 1, 2
b, 1, 22
c, 1, 23
a, 2, na
b, 2, na
c, 2, na

df.1 = structure(list(region = c("a", "b", "c", "a", "b", "c"), time = c(1L, 
1L, 1L, 2L, 2L, 2L), value = c(2L, 22L, 23L, NA, NA, NA)), .Names = c("region", 
"time", "value"), row.names = c(NA, -6L), class = "data.frame")

df.2

region, time, value
a, 2, 45
b, 2, 54
c, 2, 56

df.2 = structure(list(region = c("a", "b", "c"), time = c(2L, 2L, 2L
), value = c(45L, 54L, 56L)), .Names = c("region", "time", "value"
), row.names = c(NA, -3L), class = "data.frame")

我正在使用merge(df.1, df.2, by=c(“region”, "time”), all.x=TRUE)

我结束了添加到df.1表的新列,但是我想只在找到匹配项时更新df.1 $ value中的值。我还需要保留df.1表中的所有值。建议表示赞赏。

所需的输出如下

region, time, value
    a, 1, 2
    b, 1, 22
    c, 1, 23
    a, 2, 45
    b, 2, 54
    c, 2, 56

0 个答案:

没有答案