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?
Paths for:
folder1: C:\folder1 folder2: C:\folder2
My trial
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.
You can do something similar using glob like you have, but with the directory names. Show activity on this post. Below function will return list of files in all the directories and sub-directories without using glob. Read from the list of files and open to read.
To list all files in a directory in R programming language we use list. files(). This function produces a list containing the names of files in the named directory. It returns a character vector containing the names of the files in the specified directories.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With