从多个文件夹读取所有脚本和数据文件 [英] Reading all scripts and data files from multiple folders
问题描述
我有两个文件夹,分别是folder1
和folder2
,每个文件夹大约有200个文件,分别是*rda
或*R
.我想从两个目录中读取所有文件和数据集.我该怎么办?
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 files and datasets from the two directories. How can I do that?
路径:
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
我知道这是一个简单的问题,但是我没有任何答案.
I know this is simple question, but I do not have any answer.
推荐答案
由于.rda
需要load
和.R
需要source
,因此我将执行以下操作:
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)
更新以便一次读取多个文件夹
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
匹配,并且在某些情况下使用ignore.case
这些文件被命名为script.r
.
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
.
这篇关于从多个文件夹读取所有脚本和数据文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!