Jake Russ
Jake Russ

Reputation: 673

Group R objects into a list

I have loaded a series of SpatialPolygonsDataFrames into my workspace. Each of the named objects has either "_adm0", "_adm1", or "_adm2" attached to the country abreviation. For Germany, this would look like "DEU_adm0", "DEU_adm1", and "DEU_adm2".

I'm trying to gather all of the "_adm0" data frames into a list which can then be operated on by ldply and fortify. I could do that with,

mylist <- list(DEU_adm0, FRA_adm0, RUS_adm0, etc...) where I write out all of the countries that I want to be included in the list.

But, how do I grab all of the "_adm0" data frames by a pattern?

I have started with the code below but it doesn't give me the desired result as writing out

adm0list <- ls()[str_detect(ls(), "_adm0")]

mylist   <- sapply(adm0list, function(x) get(x))

or alternatively,

mylist   <-  mget(adm0list, .GlobalEnv)

I do get a list of objects with the sapply method, and using mget(), but I'm not seeing why those lists are different than using list() with the object names directly. I suspect the answer to that question will tell me why ldply + fortify works with the list()method but not the other two.

Upvotes: 3

Views: 2216

Answers (1)

Simon O&#39;Hanlon
Simon O&#39;Hanlon

Reputation: 59970

You could use the pattern argument of ls and then use the @ extractor for the data.frame portion of your SPDF objects...

#  Construct list of objects wtih mget
ll <- mget( ls( pattern = "_adm0" ) )

#  Extract data.frames
out <- lapply( ll , function(x) x@data )

Upvotes: 5

Related Questions