【问题标题】:cbind and match in data.frame structure在 data.frame 结构中 cbind 和 match
【发布时间】:2020-07-09 09:07:56
【问题描述】:

由于我是 包的新手,我想将我通常在下面的 结构中执行的操作复制到 data.table 结构中。

Dta     <- data.frame(Customer = c("Javier","Oscar","Ivan","Peter"),Type_of_Customer=LETTERS[c(1,1:3)])
Dtb     <- data.frame(Customer = c("Javier","Oscar","Ivan","Jack"),Zone=5:8,District=100:103)
Result  <- cbind(Dtb[match(Dtb[,"Customer"],Dta[,"Customer"]),c("Zone","District")],Dta)


ww     <- which(is.na(Result[,"Zone"]))
if(length(ww) > 0){
  Result[ww,"Zone"] <- "Not in Dtb"
}

ww     <- which(is.na(Result[,"District"]))
if(length(ww) > 0){
  Result[ww,"District"] <- "Not in Dtb"
  }

所以如果我有 DtaDtb 作为 data.table 结构,那该怎么办? (注意:在实际示例中,我有大约 1000 万行,所以我需要更省时的解决方案)

Dta     <- data.table(Custumer = c("Javier","Oscar","Ivan","Peter"),Type_of_Customer=LETTERS[c(1,1:3)])
Dtb     <- data.table(Custumer = c("Javier","Oscar","Ivan","Jack"),Zone=5:8,District=100:103)

谢谢。

【问题讨论】:

  • 变量“Result”是我期望的输出。
  • 我发布了一个解决方案,请检查

标签: data.table data.frame r dataframe data.table data-manipulation


【解决方案1】:

我们可以使用连接 onthee 'Customer' 并将 NA 元素替换为 'Not in 'Dtb' 字符串

Dtb[Dta, on = .(Custumer)][, c("Zone", "District") := 
    .(as.character(Zone), as.character(District))
     ][is.na(Zone), c("Zone", "District") := "Not in Dtb"][]
#    Custumer       Zone   District Type_of_Customer
#1:   Javier          5        100                A
#2:    Oscar          6        101                A
#3:     Ivan          7        102                B
#4:    Peter Not in Dtb Not in Dtb                C

【讨论】:

  • 效果很好,非常感谢!您能否推荐一个更好的 data.table 教程或知识来源,我可以从中学习?
  • @MaxMolina 你可以查看data.table的小插曲
猜你喜欢
  • 2023-03-31
  • 2018-06-06
  • 2015-03-12
  • 1970-01-01
  • 1970-01-01
  • 2016-05-09
  • 2013-03-20
相关资源
最近更新 更多