How can I make a list of all dataframes that are in my global environment?

后端 未结 6 2292
不知归路
不知归路 2020-11-28 14:02

I am trying to use rbind on them. But I need a list of all the dataframes that are already in my global environment. How can I do it?

Code

相关标签:
6条回答
  • 2020-11-28 14:17

    From your posted code, I would recommend you start a new R session, and read the files in again with the following code

    do.call(rbind, lapply(list.files(pattern = ".csv"), read.csv))
    
    0 讨论(0)
  • 2020-11-28 14:19

    To improve MentatOfDune's answer (great username by the way):

    ls()[sapply(ls(), function(x) any(class(get(x)) == 'data.frame'))]
    

    or even more robust:

    ls()[sapply(ls(), function(x) any(is.data.frame(get(x))))]
    

    This also supports tibbles (created with dplyr for example), because they contain multiple classes, where data.frame is one of them.

    0 讨论(0)
  • 2020-11-28 14:20

    The ls function lists all things in your environment. The get function gets a variable with a given name. You can use the class function to get the class of a variable.

    If you put them all together, you can do this:

    ls()[sapply(ls(), function(x) class(get(x))) == 'data.frame']
    

    which will return a character vector of the data.frames in the current environment.

    0 讨论(0)
  • 2020-11-28 14:22

    This function should return a proper list with all the data.frames as elements

    dfs <- Filter(function(x) is(x, "data.frame"), mget(ls()))
    

    then you can rbind them with

    do.call(rbind, dfs)
    

    Of course it's awfully silly to have a bunch of data.frames lying around that are so related that you want to rbind them. It sounds like they probably should have been in a list in the first place.

    I recommend you say away from assign(), that's always a sign things are probably afoul. Try

    temp <- list.files(pattern="*.csv")
    dfs <- lapply(temp, read.csv)
    

    that should return a list straight away.

    0 讨论(0)
  • 2020-11-28 14:29

    This is a slight improvement on MentatOfDune's answer, which does not catch data.frames with multiple classes:

    ls()[grepl('data.frame', sapply(ls(), function(x) class(get(x))))]
    
    0 讨论(0)
  • 2020-11-28 14:30

    If you only have data.frames with the same number of columns and column names in you global environment, the following should work (non-data.frame object don't matter):

    do.call(rbind, eapply(.GlobalEnv,function(x) if(is.data.frame(x)) x))
    
    0 讨论(0)
提交回复
热议问题