【问题标题】:Extracting from a list of list of data.frames in R?从R中的data.frames列表中提取?
【发布时间】:2020-02-13 15:22:11
【问题描述】:

我有一个名为 G 的 data.frames 列表。

在 BASE R 中,我想知道如何分别提取 AABB 中的元素 dintSD data.frame colnames 包含 short del1del2(请参阅下面的我的所需输出) ?

G <- list(AA = list(short = data.frame(dint = 5:7, SD = 0:2), short..2 = NULL, del1 = data.frame(dint = 1:3, SD = 2:4), 
               del1..2 = NULL, del2 = NULL), 

          BB = list(short = data.frame(dint = 1:4, SD = 2:5), short..2 = NULL, del1 = 
                 data.frame(dint = 5:6, SD = 3:4), del1..2 = NULL, del2 = data.frame(dint = 6, SD = 1)) )

我想要的输出是:

# dints:
dints = list(
short = list(AA = c(short = 5:7), BB = c(short = 1:4)),
 del1 = list(AA = c(del1 = 1:3), BB = c(del1 = 5:6)),
 del2 = list(AA = c(del2 = NULL), BB = c(del2 = 6)))


# SDs:
SDs = list(
short = list(AA = c(short = 0:2), BB = c(short = 2:5)),
 del1 = list(AA = c(del1 = 2:4), BB = c(del1 = 3:4)),
 del2 = list(AA = c(del2 = NULL), BB = c(del2 = 1)))

【问题讨论】:

    标签: r list function loops dataframe


    【解决方案1】:

    我认为这个函数应该提取你需要的东西。

    foo <- function(G, val="dint", cols = c("short", "del1", "del2")) {
      named <- function(x, n) {if (is.null(x)) x else setNames(list(x), n)}  
      Map(function(col) Map(function(n) named(G[[n]][[col]][[val]], col), names(G)), cols)
    }
    
    dints <- foo(G, "dint")
    SDs <- foo(G, "SD")
    

    对于最里面的值,我使用列表而不是命名向量。不确定删除 ..2 值的逻辑是什么,所以我只是创建了一个参数来指定要提取的子值。

    【讨论】:

    • 您可以使用cols = 参数选择要捕获的内容。我只是用您在所需输出中使用的值对其进行了硬编码。
    • 我不明白为什么这是不可能的。免费免费更改代码以做您喜欢的事情。此版本提供了您在原始问题中要求的输出。
    猜你喜欢
    • 2017-06-10
    • 2017-12-12
    • 2019-12-29
    • 1970-01-01
    • 2019-11-10
    • 1970-01-01
    • 2020-02-07
    • 2017-02-26
    • 1970-01-01
    相关资源
    最近更新 更多