26

我有两个文件夹,folder1每个文件夹folder2大约有 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 

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

4

3 回答 3

52

由于.rdarequiresload.Rrequires 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在行尾的 a,以及ignore.case在某些文件被命名的情况下使用,例如,script.r

于 2012-04-24T04:38:46.370 回答
5
for (f in list.files(pattern="*.R")) {
    source(f)
}
for (f in list.files(pattern="*.rda")) {
    load(f)
}
于 2012-04-24T04:06:17.127 回答
3

如果要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!
于 2019-12-02T21:28:21.163 回答