【发布时间】:2014-06-18 17:17:29
【问题描述】:
我在 R 中有两个 data.tables 如下:
DT_A 包含列 sid、date、value1、value2,其中 sid 是主键,date 是辅助键。
DT_B 具有列 sid、date1、date2、date3、....、date12。这里sid 是主键,因此每一行对应唯一的sid,其他列名对应DT_A 中的辅助键。
我想在DT_A 中添加另一列,其中第 i 行包含表 DT_B[sid_i, date_i] 中的相应元素
以下是示例代码和所需的输出:
require(data.table)
DT_A <- data.table(sid = c(1,2,3,4,5,1,3),
date = c("Jan 2012", "Feb 2012", "April 2012", "May 2012",
"Dec 2012", "Feb 2012", "Oct 2012"),
value1 = rep("1", 7),
value2 = rep("1", 7))
DT_B <- data.table(sid = as.character(c(1,2,3,4,5)),
"Jan 2012" = rep("1", 5),
"Feb 2012" = rep("2", 5),
"March 2012" = rep("3", 5),
"April 2012" = rep("4", 5),
"May 2012" = rep("5", 5),
"June 2012" = rep("6", 5),
"July 2012" = rep("7", 5),
"Aug 2012" = rep("8", 5),
"Sept 2012" = rep("9", 5),
"Oct 2012" = rep("10", 5),
"Nov 2012" = rep("11", 5),
"Dec 2012" = rep("12", 5))
#Set Keys
setkey(DT_A, sid, date)
setkey(DT_B, sid)
#Define Function fun1
fun1 <- function(x){
tryCatch(DT_B[x[1], x[2], with=FALSE], error = function(e) NULL)
}
#Desired Output
DT_A$newCol <- sapply(apply(DT_A, 1, fun1),"[[",1)
DT_A
虽然我当前的方法适用于这个小例子,但我的实际 DT_A 有 2000 万行。这种方法完全挂在那里。我们可以使用data.table 或任何其他方法以更有效的方式执行此操作吗?
【问题讨论】:
-
你没有提供
DT_A -
抱歉错了,已经这样做了
-
我认为这个问题应该改写。这不是关于按行操作,而是关于重塑和合并。
标签: r data.table