Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setwd() in the current working dir

Tags:

r

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.

like image 339
Fuv8 Avatar asked Feb 22 '13 14:02

Fuv8


3 Answers

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 )
like image 84
Anthony Damico Avatar answered Sep 20 '22 01:09

Anthony Damico


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

like image 23
mjshaw Avatar answered Sep 19 '22 01:09

mjshaw


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.

like image 31
Greg Snow Avatar answered Sep 18 '22 01:09

Greg Snow