【问题标题】:Create standard data.table columns given multiple inputs在给定多个输入的情况下创建标准 data.table 列
【发布时间】:2018-02-18 00:32:00
【问题描述】:

我正在编写一个重写列名的函数,以便在标准中输出 data.table。输入是用户提供的 data.tables,可能有几个名称不同。

这是所有输入 data.tables 的输出格式:

length    width    height    weight

输入的 data.tables 可能看起来像,例如

input_dt = data.table(
  length = 194,
  wide = 36,
  tall = 340,
  kilogram = 231.2
)

我的函数会将此 data.table(或 data.frame)作为输入,并更改列,输出此 data.table:

length    width    height    weight
194       36      340     231.2

我为检查可能名称的函数创建了一个key

key = list(
    length = c('long'),
    width = c('girth', 'WIDTH', 'wide'),
    height = c('tall', 'high'),
    weight =  c('Weight', 'WEIGHT', 'kilogram', 'pound', 'kilograms', 'pounds')
)

现在,在函数内,我可以通过检查交集来检查input_dt的输入列名称是否需要更改:

> intersect(names(input_dt), unlist(key))
[1] "wide"     "tall"     "kilogram"

然后适当地改变这些。我的问题是:

编写这个自定义函数会充满 for 循环,而且效率很低。给定自定义的值“键”,是否还有其他对 data.table 更友好的解决方案可用?

【问题讨论】:

    标签: r data.table multiple-columns


    【解决方案1】:

    key 保留为list,而不是data.table,然后合并:

    # easier to edit this list if you need to update your keywords later
    key_list = list(
      length = c('long'),
      width  = c('girth', 'WIDTH', 'wide'),
      height = c('tall', 'high'),
      weight = c('Weight', 'WEIGHT', 'kilogram', 'pound', 'kilograms', 'pounds')
    )
    # build into data.table
    keyDT = data.table(
      # can't name a column key
      key_name = rep(names(key_list), lengths(key_list)),
      synonym = unlist(key_list),
      # easier merging
      key = 'synonym'
    )
    
    # nomatch = 0 to skip unmatched columns
    keyDT[.(names(input_dt)), setnames(input_dt, synonym, key_name), nomatch = 0L]
    

    之后是input_dt

    input_dt
    #    length width height weight
    # 1:    194    36    340  231.2
    

    为了稳健性,您可能希望将 self 添加到 key_list(例如,length = c('length', 'long'));这样,如果input_dt 的名称中包含尚未见过的synonym,您就可以更轻松地抛出错误/警告。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-16
      • 2020-02-03
      • 2018-10-29
      • 2018-09-16
      • 2020-12-23
      • 1970-01-01
      相关资源
      最近更新 更多