问题描述
使用lapply可以正常工作。 但是,有了庞大的数据集,它要运行数小时。
有没有更快的选择? 谢谢!
MWE:
require(data.table)
# Dummy data.
dt_lookup <- data.table(cls_old=c(1:5),cls_new=c(5:1)) # Lookup-Table,the real data has different and non-continous entries.
dt <- data.table(cls=c(5:1),data=c(1,2,3,4,5)) # Table in which data shall be replaced depending on the lookup-table.
# Function to get the new column entry for every row based on the lookup-table.
get_new_label <- function(cls) {
return(dt_lookup[cls_old==cls]$cls_new)
}
# Actual replacement of values.
dt <- dt[,cls:=lapply(cls,get_new_label)]
解决方法
如果我没有误会,可以进行简单的加入:
dt[dt_lookup,cls := i.cls_new,on = .(cls = cls_old)]
dt
# cls data
#1: 1 1
#2: 2 2
#3: 3 3
#4: 4 4
#5: 5 5
您应该花一些时间研究数据,表渐晕和文档。
,您可以使用match
来实现查找表。
i <- match(dt$cls,dt_lookup$cls_old)
j <- !is.na(i)
dt$cls[j] <- dt_lookup$cls_new[i[j]]
dt
# cls data
#1: 1 1
#2: 2 2
#3: 3 3
#4: 4 4
#5: 5 5
也可以看看fast R lookup table。