我中的R 2个data.tables如下新的列:创建Data.Table使用行操作ř
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' –
对不起,现在已经做了 – user3750170
我觉得应该重新编写这个问题。这不是关于做明智的行动,这是关于重塑和合并。 – geneorama