R 在给定多个输入的情况下创建标准data.table列
我正在编写一个函数,它重新写入列名,以便以标准格式输出data.table。输入是用户提供的数据。表可能因几个名称不同而不同 以下是所有输入数据的输出格式。表:R 在给定多个输入的情况下创建标准data.table列,r,data.table,multiple-columns,R,Data.table,Multiple Columns,我正在编写一个函数,它重新写入列名,以便以标准格式输出data.table。输入是用户提供的数据。表可能因几个名称不同而不同 以下是所有输入数据的输出格式。表: length width height weight 输入数据表可能看起来像,例如 input_dt = data.table( length = 194, wide = 36, tall = 340, kilogram = 231.2 ) 我的函数将此data.table(或data.frame)
length width height weight
输入数据表可能看起来像,例如
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 = 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循环,而且效率很低。如果提供自定义的“键”值,是否还有其他数据表友好的解决方案 保留
键
不是作为列表
而是作为数据。表
,然后合并:
# 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]
之后使用输入\u dt
:
input_dt
# length width height weight
# 1: 194 36 340 231.2
为确保健壮性,您可能希望将self添加到
键列表中(例如,length=c('length','long')
);这样,如果input\u dt
的名称中有一个尚未看到的同义词
,您就可以更容易地抛出错误/警告。保留键
不是作为列表,而是作为数据。表
,然后合并:
# 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]
之后使用输入\u dt
:
input_dt
# length width height weight
# 1: 194 36 340 231.2
为确保健壮性,您可能希望将self添加到键列表中(例如,length=c('length','long')
);这样,如果input\u dt
的名称中有一个尚未看到的同义词,则可以更容易地抛出错误/警告