r - 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)]
解决方案
如果我没有误会,你可以做一个简单的加入:
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 插图和文档。
推荐阅读
- android - 自定义通知显示类似图像
- python - 无法执行 ansible playbook(未安装 libselinux python)
- python - 输入字典和字典列表并仅在存在整数时替换
- sap-gui - 信息窗口的 SAP GUI 脚本
- reactjs - npm start 在编译期间抛出错误
- java - 如何从android中的url解析json
- scikit-learn - Sklearn:线性回归
- java - 如何使用 Selenium 和 Java 定位并单击选择布尔复选框
- ios - UITesting 只是失败了,没有更多的上下文就没有编写测试
- c++ - 结果不是我所期望的