首页 > 解决方案 > R:lapply with data.table 慢,有更快的选择吗?

问题描述

我有一个表,我想在其中使用查找表替换单个列的值。

使用 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)]

标签: rdata.tablelapply

解决方案


如果我没有误会,你可以做一个简单的加入:

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

您真的应该花一些时间研究 data.table 插图和文档。


推荐阅读