当DT1.x和DT2.x在R中匹配时,用DT2.y替换DT1.x

时间:2017-03-03 19:44:30

标签: r data.table

我想使用R。

中的数据表来执行此操作

所以我从这个开始

     dtMain
           Name      state
    1: CompanyC         CA
    2: CompanyM         MN
    3: CompanyC1 California
    4: CompanyT         TX

     statesFile
       stateExpan state
    1:      Texas    TX
    2:  Minnesota    MN
    3: California    CA

dtMain$State == statesFile$state位置,我想将dtMain$State替换为statesFile$stateExpan 得到这个

      dtMain
           Name      state
    1: CompanyA California
    2: CompanyB  Minnesota
    3: CompanyC California
    4: CompanyD      Texas

此处创建2个文件的代码

library(data.table)
dtMain <- data.table(Name  = c("CompanyA"  ,"CompanyB","CompanyC","CompanyD"),
                 state = c("CA","MN","California","TX"))
statesFile <- data.table( stateExpan = c("Texas","Minnesota","California"),
                          state = c("TX","MN","CA"))

我的问题是这个问题的下一个层面 R finding rows of a data frame where certain columns match those of another 我正在寻找一个数据表解决方案。

1 个答案:

答案 0 :(得分:3)

使用更新联接:

dtMain[statesFile, on=.(state), state := i.stateExpan ]

i.*前缀表示它来自i中的x[i, on=, j]表。这是可选的。

有关详细信息,请参阅?data.table