Accessing data in different folders in a working directory in r

directory, r

Solution

Just prepend the sub-directory to the file name.

setwd("~/Dropbox/Ril_1/")

# Find the filenames in the two subdirectories
score.files <- dir("Score/", pattern="txt")
setup.files <- dir("Setup/", pattern="txt")

# Go through the score files and put them in a list 
scores <- sapply(score.files, function(f)
      {
      res <- read.table(paste0("Score/", f))
      res
      }, simplify=F)

# Go through the setup files and do the same
setup <- sapply(setup.files, function(f)
      {
      res <- read.table(paste0("Setup/", f))
      res
      }, simplify=F) 

Now you can access the content of each file using the `[[]]` operator, such as:

scores[[3]]

Problem

So I set my working directory, a folder called "Ril_1". ``` setwd("~/Dropbox/Ril_1/") ``` Within this folder "Ril_1", there are two .R script files, another folder named "Score" and another folder named "Setup". In both "Score" and "Setup" folders, there are 21 .txt files that I would like to output as a list of 21 data frames, each .txt file being a data frame. In order to do that, I've been setting the working directory three different times... ``` setwd("~/Dropbox/Ril_1/") setwd("~/Dropbox/Ril_1/Score") #read in .txt files from "Score" file setwd("~/Dropbox/Ril_1/Setup") #now read in .txt files from "Setup" file ``` Is there a way I can set the working directory to "Ril_1" folder then be able to read in data that's in "Score" and "Setup" folders (outputting each as a list of 21 data frames) as well as the two .R script files? Thank you in advance!

Original source