我有两个文件夹,folder1
并folder2
与周围的200个文件每个要么*rda
或*R
.我想从两个目录中读取所有文件和数据集.我怎样才能做到这一点?
路径:
folder1: C:\folder1
folder2: C:\folder2
Run Code Online (Sandbox Code Playgroud)
我的审判
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
Run Code Online (Sandbox Code Playgroud)
我知道这是一个简单的问题,但我没有任何答案.
A5C*_*2T1 41
既然.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)
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
另请注意$
,在搜索模式的末尾使用,以确保它仅匹配,例如,.R
在行的末尾匹配,以及ignore.case
在某些文件被命名的情况下使用,例如,script.r
.
for (f in list.files(pattern="*.R")) {
source(f)
}
for (f in list.files(pattern="*.rda")) {
load(f)
}
Run Code Online (Sandbox Code Playgroud)
如果你想使用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!
Run Code Online (Sandbox Code Playgroud)