从多个文件夹中读取所有脚本和数据文件

时间:2012-04-24 03:53:19

标签: r file-io

我有两个文件夹folder1folder2,每个文件夹大约有200个文件,分别是*rda*R。我想从两个目录中读取所有文件和数据集。我怎么能这样做?

路径:

folder1:  C:\folder1
folder2:  C:\folder2 

我的试用

setwd("C:/folder1")
myls <- ls() # do work as this will only list that are already loaded in the system 
setwd("C:/folder2")
myls2 <- ls()
myls  # do work as this will only list that are already loaded in the system 

我知道这是一个简单的问题,但我没有任何答案。

3 个答案:

答案 0 :(得分:39)

由于.rda需要load.R需要source,我会这样做:

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

一次从多个文件夹中读取的更新

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)

另请注意,在搜索模式的末尾使用$,以确保它只匹配一行的末尾.R,并使用{{1如果某些文件被命名,例如ignore.case

答案 1 :(得分:4)

for (f in list.files(pattern="*.R")) {
    source(f)
}
for (f in list.files(pattern="*.rda")) {
    load(f)
}

答案 2 :(得分:1)

如果您想改用tidyverse,则可以使用map函数来简化:

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!