Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading all scripts and data files from multiple folders

Tags:

file-io

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?

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.

like image 791
SHRram Avatar asked Apr 24 '12 03:04

SHRram


People also ask

How do I read multiple text files from multiple folders in Python?

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.

How do I read all files in a folder in R?

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.


1 Answers

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) 

Update for reading from multiple folders at once

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.

like image 103
A5C1D2H2I1M1N2O1R2T1 Avatar answered Oct 17 '22 06:10

A5C1D2H2I1M1N2O1R2T1