使用lapply在子目录中获取多个R脚本

时间:2016-11-01 12:56:06

标签: r

这些是我目录中的文件夹

128    128-1-32  16384    16384-1-36  4096-1     512    512-1-65  65536-1
128-1  128tbw1   16384-1  4096        4096-1-36  512-1  65536

他们每个人都有一个.7.R代码,从每个文件夹加载文件并创建图像。我希望我的脚本进入每个文件夹然后

source('a7.R') 

然后退出该文件夹并重复所有文件夹的过程。我现在正在手动执行此操作,这真的很无聊。这可能与R?

我尝试过像这样的解决方案

#!/usr/bin/Rscript

 lapply(list.files(full.names=TRUE, recursive = TRUE, pattern = "^a7\\.R$"), source)

milenko@milenko-desktop:~/jbirp/mt07$ Rscript s.R
list()

coffeinejunky的解决方案无效

#!/usr/bin/Rscript

foo <- function(directory) { setwd(directory); source(a7.R) }
do.call("foo", list(directory= 128 128-1-32  16384 16384-1-36  4096-1 512 512-1-65 65536-1  128-1 128tbw1 16384-1  4096 4096-1-36  512-1  65536))

    source('n.R')
Error in source("n.R") : n.R:2:33: unexpected numeric constant
1: foo <- function(directory) { setwd(directory); source(a7.R) }
2: do.call("foo", c(directory= 128 128

如果我改变这样的列表

   do.call("foo", list(directory= "./128" "./128-1" "./128-1-32" "./128tbw1" "./16384" "./16384-1" "./16384-1-36" "./4096" "./4096-1" "./4096-1-36"  "./512" "./512-1" "./512-1-65" "./65536" "./65536-1"))

我得到了

Error in source("n.R") : n.R:2:40: unexpected string constant
1: foo <- function(directory) { setwd(directory); source(a7.R) }
2: do.call("foo", list(directory= "./128" "./128-1"

                        ^

这是我列出路径时的结果

> list.dirs(path = ".", full.names = TRUE)
 [1] "."            "./128"        "./128-1"      "./128-1-32"   "./128tbw1"   
 [6] "./16384"      "./16384-1"    "./16384-1-36" "./4096"       "./4096-1"    
[11] "./4096-1-36"  "./512"        "./512-1"      "./512-1-65"   "./65536"     
[16] "./65536-1"

我需要多次更改目录并在每个目录中执行相同的操作。这是不是很好用?

2 个答案:

答案 0 :(得分:2)

以下内容应该有效:

directories <- list.dirs(path=".", full.names = T)
# you need to make sure this contains the relevant directories
# otherwise you need to remove irrelevant directories

foo <- function(x) {
  old <- setwd(x) # this stores the old directory and changes into the new one
  source("a7.R")
  setwd(old) 
}

lapply(directories, foo)

可替换地,

for(folder in directories) foo(folder)

答案 1 :(得分:0)

这将为每个a7.R文件提供源,并将工作目录临时设置为源文件的文件夹。

a7files <- list.files(full.names=TRUE, recursive = TRUE, pattern = "^a7\\.R$")
sapply(a7files, source, chdir = TRUE)

来自?source

chdir符合逻辑;如果TRUEfile是路径名,则将R工作目录临时更改为包含file的目录以进行评估。