Reading all scripts and data files from multiple folders

后端 未结 3 1058
小鲜肉
小鲜肉 2020-12-23 17:37

I have two folders, folder1 and folder2 with around 200 files each that are either *rda or *R. I want to read all of the

相关标签:
3条回答
  • 2020-12-23 18:11
    for (f in list.files(pattern="*.R")) {
        source(f)
    }
    for (f in list.files(pattern="*.rda")) {
        load(f)
    }
    
    0 讨论(0)
  • 2020-12-23 18:15

    Since .rda requires load and .R requires source, I would do something like this:

    file.sources = list.files(pattern="*.R")
    data.sources = list.files(pattern="*.rda")
    sapply(data.sources,load,.GlobalEnv)
    sapply(file.sources,source,.GlobalEnv)
    

    Update for reading from multiple folders at once

    file.sources = list.files(c("C:/folder1", "C:/folder2"), 
                              pattern="*.R$", full.names=TRUE, 
                              ignore.case=TRUE)
    data.sources = list.files(c("C:/folder1", "C:/folder2"),
                              pattern="*.rda$", full.names=TRUE, 
                              ignore.case=TRUE)
    sapply(data.sources,load,.GlobalEnv)
    sapply(file.sources,source,.GlobalEnv)
    

    Notice also the use of $ at the end of the search pattern, to make sure it matches only, say, a .R at the end of a line, and the use of ignore.case in case some of the files are named, say, script.r.

    0 讨论(0)
  • 2020-12-23 18:17

    If you want to use tidyverse instead, you could use the map function to simplify:

    my_path <- c("/path/to/files/")             # set your path
    source_files <- list.files(my_path, "*.R$")  # locate all .R files
    map(paste0(my_path, source_files), source)  # source all your R scripts!
    
    0 讨论(0)
提交回复
热议问题