【发布时间】:2020-12-08 18:06:36
【问题描述】:
我有一个表,我想在其中使用查找表替换单个列的值。
使用 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)]
【问题讨论】:
-
我认为这通常被称为“update join”,所以在你的搜索中使用它(连同 R 和 data.table)你会找到的。跨度>
标签: r data.table lapply