简体   繁体   English

从列表列表中提取数据[R]

[英]Extract data from list of lists [R]

I have a list of lists (mydata$notes) that I want to extract data from. 我有一个列表(mydata $ notes),我想从中提取数据。 Code looks like this, if I want to extract "location" - this works fine. 代码看起来像这样,如果我想提取“位置” - 这很好。

location <- unlist (lapply(mydata$notes, function(e) e$location))

Now, I might have more variables I want to extract, say a vector of 20, "location", "var1", "var2", "var3" and so on, in an atomic vector 现在,我可能有更多我想要提取的变量,例如20的矢量,“位置”,“var1”,“var2”,“var3”等等,在原子矢量中

names(unlist(mytree$notes[[1]]))

How can I loop my first code to extract all variables given in this names-variable? 如何循环我的第一个代码来提取这个名称变量中给出的所有变量?

Cheers 干杯

Define a vector to hold the list elements which you want to extract. 定义一个向量来保存要提取的列表元素。 Then call unlist() on each list which is processed by your call to lapply() . 然后在每个列表上调用unlist() ,该列表由您调用lapply()

vars <- c("location", "var1", "var2", "var3")

location <- unlist (lapply(mydata$notes,
                           function(e) {
                               unlist(e[vars])
                           }))

Notice that the only real change I made is that instead of returning the atomic vector e$location I instead return a vector consisting of several collapsed elements from each list. 请注意,我所做的唯一真正的改变是,不是返回原子向量e$location而是返回一个由每个列表中的几个折叠元素组成的向量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM