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
for (f in list.files(pattern="*.R")) {
source(f)
}
for (f in list.files(pattern="*.rda")) {
load(f)
}
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)
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.
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!