【问题标题】:Appending new columns to table based on matching to second table根据与第二个表的匹配将新列附加到表中
【发布时间】:2016-12-17 04:57:28
【问题描述】:

我有两个表 selectVDem 和 DT。

DT 有列标记国家、月-年和年

       Country MonthofDate Size Year
   1:    Benin  1997-01-01   18 1997
   2:    Benin  1997-02-01   18 1997
   3:    Benin  1997-03-01   18 1997
   4:    Benin  1997-04-01   18 1997
   5:    Benin  1997-05-01   18 1997
  ---                               
3506: Zimbabwe  2015-07-01   38 2015
3507: Zimbabwe  2015-08-01   38 2015
3508: Zimbabwe  2015-09-01   42 2015
3509: Zimbabwe  2015-10-01   42 2015
3510: Zimbabwe  2015-11-01   42 2015

而 selectVDem 具有以下标题

Year Country EqualityResources EqualityProtec PercentSufferage   LocalGov  RegionGov ExecCorrupt PolCorrupt

我想将 EqualityResources EqualityProtec PercentSufferage LocalGov RegionGov ExecCorrupt PolCorrupt 值附加到 DT 表的末尾,作为基于年份和国家值匹配的新列。有什么方法可以在不使用 for 循环的情况下做到这一点?我已经尝试了两种方法。

DT$EqualityResources <- subset(DT$Country == selectVDem$Country & DT$Year == `selectVDem$Year, select =  EqualityResources)`

这会导致错误

Error in subset.default(DT$Country == selectVDem$Country & DT$Year ==  : 
  argument "subset" is missing, with no default
In addition: Warning messages:
1: In is.na(e1) | is.na(e2) :
  longer object length is not a multiple of shorter object length
2: In `==.default`(DT$Country, selectVDem$Country) :
  longer object length is not a multiple of shorter object length
3: In DT$Year == selectVDem$Year :
  longer object length is not a multiple of shorter object length

我也试过写一个函数并使用apply函数

getVDem <- function(vDemVal, country, year, vDem){
  result <- vDem[vDem$Country == country & vDem$Year == year,]
  finalResult <- vDem$vDemVal
  return(finalResult)
}

DT$EqualityResources <- apply(DT, 1, getVDem(selectVDem, DT$Country, `DT$Year,'EqualityResources'))#subset(selectVDem,DT$Country == Country & DT$Year == Year, select = EqualityResources)`

这给了我错误

vDem$Country 中的错误:$ 运算符对原子向量无效

我该怎么办?

【问题讨论】:

  • 像合并吗?您正在尝试根据国家和年份将 selectVDem 中的列合并到 DT - 如果我错了,请纠正我
  • 有点,它不能是合并,因为 DT 的行数比 selectVDem 多得多,因为 DT 的每个月-年都有一行,而 selectVDem 只有一年的行。但是,我想知道是否可以从 selectVDem 获取贝宁 1997 年的信息并将其添加到 DT 中 1997 年的所有 12 行。

标签: r match


【解决方案1】:

尝试按列进行可能会造成混乱。您可以使用 dplyr 的 join 函数组,很可能是 left_join。拥有匹配的列名可以使连接自动确定“by”参数,但是如果你有匹配的列名和不同的列内容,请小心!

library(dplyr)
newDT <- left_join(DT, selectVDem)

left_join 合并的优点是您不包含左侧对象中不存在的任何类别(在您的情况下为年份或国家/地区)。自动化 by 参数也是一个优势。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-03
    • 1970-01-01
    • 2022-12-20
    • 2020-03-29
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多