【问题标题】:R: lapply with data.table slow, is there a faster alternative?R:lapply with data.table 慢,有更快的选择吗?
【发布时间】: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


【解决方案1】:

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

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 插图和文档。

【讨论】:

    【解决方案2】:

    您可以使用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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-07
      • 2010-10-25
      • 2011-12-16
      • 2019-11-24
      • 2011-03-30
      • 2021-10-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多