Extract data from list of lists [R]

╄→尐↘猪︶ㄣ 提交于 2019-12-24 16:09:29

问题


I have a list of lists (mydata$notes) that I want to extract data from. 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

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

How can I loop my first code to extract all variables given in this names-variable?

Cheers


回答1:


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

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.



来源:https://stackoverflow.com/questions/36492452/extract-data-from-list-of-lists-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!