22

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
    – akrun
    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.
    – akrun
    Nov 4, 2014 at 15:26
  • Could you post the error as well.
    – akrun
    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)
    – akrun
    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 Nov 4, 2014 at 15:46

1 Answer 1

17

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.