How can I access all objects of class data.frame inside .GlobalEnv in R

后端 未结 4 838
醉话见心
醉话见心 2021-01-25 03:12

I have 8,000 data.frames inside my global environment (.GlobalEnv) in R, for example

head(ls(.GlobalEnv))
#[1] \"db1\" \"db2\" \"db3\"          


        
4条回答
  •  南方客
    南方客 (楼主)
    2021-01-25 03:46

    You could use a combination of eapply and mget to put all data.frames that are present in the global environment in a list:

    x <- eapply(.GlobalEnv, 'is.data.frame')
    dflist <- mget(names(x[unlist(x)]), .GlobalEnv)
    

    Then you can use for example lapply(dflist, ...) to run a regression on each of them.


    A very concise alternative approach contributed by @RichardScriven in the comments is:

    dflist <- Filter(is.data.frame, as.list(.GlobalEnv))
    

提交回复
热议问题