给出多个输入,创建标准data.table列

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了给出多个输入,创建标准data.table列相关的知识,希望对你有一定的参考价值。

我正在编写一个函数,它重写列名以便在标准中输出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循环,效率非常低。是否有其他更多数据。可用的友好解决方案,给定一个自定义的“关键”值?

答案

保持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

为了获得稳健性,您可能希望将自我添加到key_list(例如,length = c('length', 'long'));这样,在input_dt名字中有一个尚未见过的synonym的情况下,你可以更容易地抛出错误/警告。

以上是关于给出多个输入,创建标准data.table列的主要内容,如果未能解决你的问题,请参考以下文章

R语言data.table导入数据实战:data.table生成新的数据列(基于已有数据列)生成多个数据列

如何删除 data.table 中的多个列?

如何根据多个by-record标准从data.table中提取特定字段?

Data.table 中的多个灵活的逻辑列比较

有没有办法在 i 中自我引用 data.table

R语言data.table导入数据实战:data.table使用字符向量创建新的数据列