R rbind data.tables 在名称向量上使用 do.call 与不同的列
R rbind data.tables with different column using do.call on vector of names
我有几个 data.tables 具有不同的列,我想 append/rowbind。结果应该是包含所有列的 data.table(不仅是显示所有 rbinded 数据集的列)。这是一个例子
library(data.table)
df1 = data.frame(a = c(1:5), b = c(6:10))
df2 = data.frame(a = c(11:15), b = c(16:20), c = LETTERS[1:5])
rbindlist(list(df1, df2), fill = TRUE)
借用@kdauria 在这个 post Combine two data frames by rows (rbind) when they have different sets of columns.
中的回答
但我只知道我的数据集是名称 c("a","b") 的向量,因为它们因场合而异。因此,我正在执行以下操作
goo <- function(...) rbind(...,fill=TRUE)
do.call(goo,sapply(c("a","b"),function(x) eval(parse(text=x))))
这完成了工作,但我在想是否有更聪明的方法来构造 do.call() 调用。
mget()
:
a = data.frame(a = c(1:5), b = c(6:10))
b = data.frame(a = c(11:15), b = c(16:20), c = LETTERS[1:5])
vn <- c("a","b")
rbindlist(mget(vn), fill = TRUE)
# a b c
# 1: 1 6 <NA>
# 2: 2 7 <NA>
# 3: 3 8 <NA>
# 4: 4 9 <NA>
# 5: 5 10 <NA>
# 6: 11 16 A
# 7: 12 17 B
# 8: 13 18 C
# 9: 14 19 D
# 10: 15 20 E
我有几个 data.tables 具有不同的列,我想 append/rowbind。结果应该是包含所有列的 data.table(不仅是显示所有 rbinded 数据集的列)。这是一个例子
library(data.table)
df1 = data.frame(a = c(1:5), b = c(6:10))
df2 = data.frame(a = c(11:15), b = c(16:20), c = LETTERS[1:5])
rbindlist(list(df1, df2), fill = TRUE)
借用@kdauria 在这个 post Combine two data frames by rows (rbind) when they have different sets of columns.
中的回答但我只知道我的数据集是名称 c("a","b") 的向量,因为它们因场合而异。因此,我正在执行以下操作
goo <- function(...) rbind(...,fill=TRUE)
do.call(goo,sapply(c("a","b"),function(x) eval(parse(text=x))))
这完成了工作,但我在想是否有更聪明的方法来构造 do.call() 调用。
mget()
:
a = data.frame(a = c(1:5), b = c(6:10))
b = data.frame(a = c(11:15), b = c(16:20), c = LETTERS[1:5])
vn <- c("a","b")
rbindlist(mget(vn), fill = TRUE)
# a b c
# 1: 1 6 <NA>
# 2: 2 7 <NA>
# 3: 3 8 <NA>
# 4: 4 9 <NA>
# 5: 5 10 <NA>
# 6: 11 16 A
# 7: 12 17 B
# 8: 13 18 C
# 9: 14 19 D
# 10: 15 20 E