访问r中工作目录中不同文件夹中的数据

hj1*_*j14 3 directory r

所以我设置了我的工作目录,一个名为"Ril_1"的文件夹.

    setwd("~/Dropbox/Ril_1/")
Run Code Online (Sandbox Code Playgroud)

在此文件夹"Ril_1"中,有两个.R脚本文件,另一个名为"Score"的文件夹和另一个名为"Setup"的文件夹.在"Score"和"Setup"文件夹中,有21个.txt文件,我想输出为21个数据帧的列表,每个.txt文件是一个数据帧.

为了做到这一点,我一直在设置工作目录三次......

    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 
Run Code Online (Sandbox Code Playgroud)

有没有办法我可以将工作目录设置为"Ril_1"文件夹然后能够读入"Score"和"Setup"文件夹中的数据(输出每个作为21个数据帧的列表)以及两个.R脚本文件?

先感谢您!

nic*_*ico 5

只需将子目录添加到文件名中.

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) 
Run Code Online (Sandbox Code Playgroud)

现在,您可以使用[[]]运算符访问每个文件的内容,例如:

scores[[3]]
Run Code Online (Sandbox Code Playgroud)