Reputation: 13
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
Upvotes: 1
Views: 6448
Reputation: 520878
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.
Upvotes: 1