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.
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 )
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With