MotaF MotaF - 1 month ago 11
R Question

Using lapply to source multiple R scripts in sub-directories

These are the folders in my 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


Each of them has a7.R code that loads files from each folder and creates images.I want my script to enter each of the folders then

source('a7.R')


then exit that folder and repeat the process for all the folders.I am doing this now manually and it is really boring.Is this possible with R?

I have tried solution like this

#!/usr/bin/Rscript

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

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


The
coffeinejunky
's solution is not working

#!/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


If i change list like this

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"))


I got

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"

^


This is what I got when I list path

> 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"


I need to change directory multiple times and perform the same operation in each of them.Is lapply good for this or not?

Answer

The following should work:

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)

Alternatively,

for(folder in directories) foo(folder)