25

I have 10 data frames in the global environment- 5 with a name pattern and other 5 with another naming pattern. I want to put the dataframes with same naming pattern into a list each (two lists - one for each pattern) so ultimately I can run checks on each of them using lapply like this :

 lapply(listofdataframes, function(x) range(x[ , "date"]))` 

The naming patterns are thus - Pattern 1 : q32013local, q42013local, q12014local, etc.

Pattern 2 : q32013national, q42013national etc.

I have used this in the past:

 Filter(function(x) is(x, "data.frame"), mget(ls()))` 

but it obviously makes a list of all data frames in global environment.

I was looking for how to use grep and ls together . I found the bash equivalent questions for it on SO here List files with certain extensions with ls and grep but no R equivalent. I did refer these two related questions but they are quite different :

Return elements of list as independent objects in global environment , How can I make a list of all dataframes that are in my global environment?

9
  • @vagabond You can extract the local and national and split on those Commented Nov 4, 2014 at 15:01
  • But you showed two patterns. So what I thought was you need all datasets with a particular pattern in one list and another in different list or a sort of nested list. Commented Nov 4, 2014 at 15:26
  • Could you post the error as well. Commented Nov 4, 2014 at 15:28
  • 3
    After creating some datasets, I was able to do this comfortably using mget(ls(pattern="q\\d+local")), but why do you need grep (not tested yet) Commented Nov 4, 2014 at 15:40
  • 2
    With object names like that I would suggest you begin the session by putting them into a list Commented Nov 4, 2014 at 15:46

2 Answers 2

20

I have used the following, obviously this will need to be repeated for each pattern.

Pattern1<-grep("local",names(.GlobalEnv),value=TRUE) Pattern1_list<-do.call("list",mget(Pattern1)) 
Sign up to request clarification or add additional context in comments.

Comments

1

This is a shorter solution inspired in the one from W.Kessler:

Pattern1_list <- list(mget(ls(pattern = "local")))[[1]] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.