6

I have a list of folders. In each folder there's an R identical script that have to run on files into the folder. I wrote the script one time and copied the script in each folder. The problem is that I have a list of around 100 folders so it is impossible to me to setwd() in the current working dir by hand. I would like to know if it is possible to set current working dir with for example a "." in this way:

setwd("/User/myname/./")

or in another easy way that tells R the current working dir instead of typing every time the folder name.

sebastian-c
  • 15,057
  • 3
  • 47
  • 93
Fuv8
  • 885
  • 3
  • 11
  • 21
  • 1
    Why did you copy an identical script in each folder and why do you need to set the working directory? What do you want to achieve? – Roland Feb 22 '13 at 14:42
  • 1
    Why not just have one script and perform its contents for each folder? Say through a loop? – sebastian-c Feb 22 '13 at 14:49
  • Hi Roland and sebastian! It is just because I start from a very big matrix (around 2.8G) so I divided it in subfolders and in each folder I run the same script because I have to do the same operations on the files. – Fuv8 Feb 22 '13 at 21:18

3 Answers3

8

how about this?

# set the working directory to the main folder containing all the directories
setwd( "/user/yourdir/" )

# pull all files and folders (including subfolders) into a character vector
# keep ONLY the files that END with ".R" or ".r"
r.scripts <- list.files( pattern=".*\\.[rR]$" , recursive = TRUE )

# look at the contents.. now you've got just the R scripts..
# i think that's what you want?
r.scripts

# and you can loop through and source() each one
for ( i in r.scripts ) source( i )
Anthony Damico
  • 5,779
  • 7
  • 46
  • 77
3

As far as I understand, you want to trigger a batch of R scripts, where the scripts are distributed across a number of folders.

Personally, I would probably write a shell script (or OS equivilent) to do this, rather than doing it in R.

for dir in /directoriesLocation/*/
do
    cat $dir/scriptName.R | R --slave --args $arg1 $arg2
done

where $dir is the the location of all directories containing the R script scriptName.R

mjshaw
  • 401
  • 2
  • 7
  • Hi! Yes, I run a .sh script that call a .bash script to run all the .R script since I'm working on cluster. – Fuv8 Feb 22 '13 at 15:04
3

In addition to the other great answers the source function has a chdir argument that will temporarily change the working directory to the one that the sourced file is in.

One option would be to create a vector with the filenames (including paths) for each of your script files, using list.files and/or other tools. Then source each of those files and letting source with chdir handle setting the working directory for you.

Greg Snow
  • 48,497
  • 6
  • 83
  • 110