【问题标题】:How to combine multiple data frames having similar variable names into one data frame?如何将具有相似变量名的多个数据框组合成一个数据框?
【发布时间】:2020-05-19 11:41:50
【问题描述】:

我试图编写一个代码来组合多个数据帧(大约 100 个),其中每个数据帧都存储有变量名 output1、output2、.....、output100。我想使用 rbind 函数将这些数据帧合并到一个数据帧中,但它不起作用,因为我必须再次编写每个变量名。

我需要一个建议,以一次性或以循环的形式编写所有变量名。

问题:我正在尝试将代码编写为 rbind(output1, output2, output3,....,output100),这非常冗长乏味。

【问题讨论】:

    标签: r


    【解决方案1】:

    您可以使用mget例子:

    调用 ls() 会为您提供工作区中的对象名称。

    ls()
    # [1] "n"       "out.lst"     "output.1"     "output.2"      "output.3"     "something.else"
    

    然后使用mget 抓取pattern=rbind 的数据帧,使用do.call

    output.long <- do.call(rbind, mget(ls(pattern="output.")))
    #            x y z
    # output.1.1 1 1 2
    # output.1.2 5 5 4
    # output.2.1 2 1 4
    # output.2.2 5 4 1
    # output.3.1 5 4 2
    # output.3.2 2 2 3
    

    玩具数据:

    set.seed(42)
    n <- 3
    out.lst <- setNames(replicate(n, data.frame(x=sample(1:5, 2), 
                                                y=sample(1:5, 2),
                                                z=sample(1:5, 2)), simplify=F),
                        paste0("output.", 1:n))
    list2env(out.lst, env=.GlobalEnv)
    

    【讨论】:

    【解决方案2】:

    如果你愿意使用 tidyverse 包,你可以将output 列一个列表,然后直接写,比如combined &lt;- bind_rows(output)。这很自然地适合使用 lapply() 首先创建数据框。

    [未经测试的代码]

    library(tidyverse)
    
    output <- lapply(1:length(inputFiles), function(x) read.csv(inputFiles[x]))
    combined <- bind_rows(output)
    

    【讨论】:

      猜你喜欢
      • 2015-11-05
      • 1970-01-01
      • 2013-01-17
      • 1970-01-01
      • 2021-12-10
      • 1970-01-01
      • 2019-04-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多