1

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

Bjørn
  • 13
  • 1
  • 4

1 Answers1

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.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • Thanks! But now my "location" variable is a character. I would like to return either a matrix or data frame with the elements specified in "vars". How do I do this? – Bjørn Apr 08 '16 at 06:19
  • Please see [this SO post](http://stackoverflow.com/questions/4227223/r-list-to-data-frame) for how to do this. – Tim Biegeleisen Apr 08 '16 at 06:21