列名称到数据框中

时间:2017-07-27 12:49:54

标签: r dataframe environment-variables names

如何创建包含所有环境对象(df)

列名称的数据框

实施例。将此3 df作为全局环境中的所有对象。

chocolate <- data.frame(a = 1, b = 2, c = 3)
banana <- data.frame(a = 2, d = 4, c = 3)
pear <- data.frame(d = 1, e = 4)

期望的输出

output <- data.frame(id = c("chocolate","banana", "pear"), 
                 v2 = c("a", "a", NA), 
                 v3 = c("b", NA, NA), 
                 v4 = c("c", "c", NA), 
                 v5 = c(NA, "d", "d"), 
                 v6 = c(NA, NA, "e"))
output

1 个答案:

答案 0 :(得分:0)

我们可以尝试

library(data.table)
lst <- mget(paste0("df", 1:3))
setnames(rbindlist(lapply(setNames(lst, seq_along(lst)), function(x) {
         x[] <- names(x)
           x}), fill = TRUE, idcol = 'id'), 2:6,  paste0("V", 1:5))[] 
#   id V1 V2 V3 V4 V5
#1:  1  a  b  c NA NA
#2:  2  a NA  c  d NA
#3:  3 NA NA NA  d  e