【问题标题】:Function to replace values in data.table using a lookup table使用查找表替换 data.table 中的值的函数
【发布时间】:2021-08-09 00:34:43
【问题描述】:

这是对这个问题的跟进:How to efficiently replace one set of values with another set of values in data.table using a lookup table?

我想创建一个函数,它采用任意 data.table dt、查找表 dtLookup 并根据查找表有效地替换(即使用 data.table 内存框架)列 col 中的所有值.

这是原始代码:

  dt <- data.table( chapter=as.character(11:15) );dt

  dtLookup <- data.table(
    old = c("11", "12", "14", "15"),
    new = c("101", "102", "105", "104")
  )

这可行(来自上面帖子的原始代码):

  dt[
    dtLookup,
    on = c(chapter = "old"),
    chapter := new
    ][]

但这不起作用:

  dt.replaceValueUsingLookup <- function(dt, col, dtLookup) {
    dt[
      dtLookup,
      on = c(as.name(col) = "old"),
      as.name(col) := new
      ]
  }

  dt %>% dt.replaceValueUsingLookup("chapter", dtLookup)

我也试过这个:

  dt[
    dtLookup,
    on = c(get(col) = "old"),
    get(col) := new
    ]

它也不起作用。

【问题讨论】:

    标签: r data.table


    【解决方案1】:

    我们不需要as.name= 左侧的对象未正确评估。相反,我们可以在onsetNames 中使用命名向量

    dt.replaceValueUsingLookup <- function(dt, col, dtLookup) {
       dt[
         dtLookup,
         on = setNames("old", col),
         (col) := new
          ]
         }
    

    -测试

    dt %>% 
        dt.replaceValueUsingLookup("chapter", dtLookup)
     
    dt
    #   chapter
    #1:     101
    #2:     102
    #3:      13
    #4:     105
    #5:     104
    

    【讨论】:

      【解决方案2】:

      为了完整起见,外键连接也可以用二元运算符==来表示。因此,替换函数可以写成

      dt.replaceValueUsingLookup <- function(dt, col, dtLut) {
        dt[dtLut, on = paste0(col, "==old"), (col) := new]
      }
      
      library(data.table)
      dt.replaceValueUsingLookup(dt, "chapter", dtLookup)[]
      
         chapter
      1:     101
      2:     102
      3:      13
      4:     105
      5:     104
      

      数据

      library(data.table)
      dt <- data.table(chapter = as.character(11:15))
      dtLookup <- data.table(old = c("11", "12", "14", "15"),
                             new = c("101", "102", "105", "104"))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-25
        • 2014-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多