从R?中的data.frames列表中提取? [英] Extracting from a list of list of data.frames in R?

查看:90
本文介绍了从R?中的data.frames列表中提取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为G的数据帧列表.

I have a list of list of data.frames called G.

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

In BASE R, I was wondering how I could separately extract elements dint and SD in AA and BB whose data.frame colnames contains short del1 and del2 (see my desired output below)?

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)))

推荐答案

我认为此函数应提取您所需的内容.

I think this function should extract what you need.

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值的逻辑是什么,所以我只是做了一个参数来指定要提取的子值.

I used lists rather than named vectors for the inner most values. Not sure what the logic was in dropping the ..2 values so I just made a parameter to specify which sub values you wanted to extract.

这篇关于从R?中的data.frames列表中提取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆