如何通过匹配R中的一个列值将数据帧值替换为另一个数据帧?

时间:2017-03-17 23:08:17

标签: r

假设我有一个这样的数据框A:

input("Hello")
with open("Test.txt",'r') as c:
    lines = c.readlines()
    c.close()
with open("Test.txt",'w') as c:
    c.truncate()
    for line in lines:
        if line.startswith("!") or line.startswith("*") == False:
            c.write(line)
        if line.startswith("!") or line.startswith("*") == True:
            new_line = line.translate({ord(c): None for c in '* !'})
            print(new_line)
            c.write(new_line)

    c.close()

和另一个数据框B是这样的:

index value1 value2
a      ss    aa
b      dd    ff
c      gg    hh
d      yy    zz
e      cc    xx

我希望将A替换为B值并更改为

index value1 value2
c      oooo  pppp
d      uuuu  vvvv

2 个答案:

答案 0 :(得分:0)

你可以这样做:

html_node

答案 1 :(得分:0)

我们可以加入on'索引'

library(data.table)
setDT(A)[B, names(A)[-1] := mget(paste0("i.", names(B)[-1])), on = .(index)]
A
#   index value1 value2
#1:     a     ss     aa
#2:     b     dd     ff
#3:     c   oooo   pppp
#4:     d   uuuu   vvvv
#5:     e     cc     xx

注意:假设“值”列为character而不是factor

数据

A <- structure(list(index = c("a", "b", "c", "d", "e"), value1 = c("ss", 
"dd", "gg", "yy", "cc"), value2 = c("aa", "ff", "hh", "zz", "xx"
)), .Names = c("index", "value1", "value2"), class = "data.frame", 
 row.names = c(NA, -5L))

B <- structure(list(index = c("c", "d"), value1 = c("oooo", "uuuu"
 ), value2 = c("pppp", "vvvv")), .Names = c("index", "value1", 
"value2"), class = "data.frame", row.names = c(NA, -2L))