【问题标题】:Apply a rbind or bind_rows conditionally to a list based on name根据名称有条件地将 rbind 或 bind_rows 应用于列表
【发布时间】:2020-09-30 05:46:56
【问题描述】:

给定一个这样的data.frame列表:

list_dfs <- list(a = mtcars, b = quakes, a = mtcars, c = USArrests)

names(list_dfs)
#> [1] "a" "b" "a" "c"

如何通过列表中的 data.frame 的名称应用函数?具体来说,我想将rbind 一起称为a 的data.frames 在这种情况下,这样结果列表只有三个元素。如果我想绑定它们,我会这样做:

do.call(rbind, list_dfs)
#> Error in rbind(deparse.level, ...): numbers of columns of arguments do not match

显然这行不通。如果列匹配,这确实有效。

list_mtcars <- list(a = mtcars, a = mtcars)
mt_bound <- do.call(rbind, list_mtcars)

我想知道如何有条件地复制 do.callrbind 片段,以便只有名为 a 的列表中的元素被行绑定。

感谢任何 tidyverse 或基本 R 解决方案。

【问题讨论】:

    标签: r


    【解决方案1】:

    list被列表的names拆分后,我们可以使用bind_rows

    library(dplyr)
    library(purrr)
    split(list_dfs, names(list_dfs)) %>%
       map(bind_rows)
    

    或在base R

    lapply(split(list_dfs, names(list_dfs)), function(dat) do.call(rbind, unname(dat)))
    

    【讨论】:

    • 可能没有很好地解释自己。这将绑定列表的每个元素。我只想绑定同名的。
    • 永远不要忘记拆分!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-06-04
    • 1970-01-01
    • 1970-01-01
    • 2013-05-08
    • 2019-09-30
    • 1970-01-01
    • 1970-01-01
    • 2012-03-02
    相关资源
    最近更新 更多