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

问题描述 投票:0回答:1

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

r data.table multiple-columns
1个回答
2
投票

保持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的情况下,你可以更容易地抛出错误/警告。

© www.soinside.com 2019 - 2024. All rights reserved.