我有一个文件夹列表。在每个文件夹中都有一个 R 相同的脚本,必须在文件夹中运行。我写了一次脚本,并将脚本复制到每个文件夹中。问题是我有大约100个文件夹,所以不可能手动设置当前工作目录setwd()。我想知道是否有可能使用例如"."设置当前工作目录,方法如下:
setwd("/User/myname/./")
或者采用另一种简单的方式,告诉R当前工作目录而不是每次都输入文件夹名称。
我有一个文件夹列表。在每个文件夹中都有一个 R 相同的脚本,必须在文件夹中运行。我写了一次脚本,并将脚本复制到每个文件夹中。问题是我有大约100个文件夹,所以不可能手动设置当前工作目录setwd()。我想知道是否有可能使用例如"."设置当前工作目录,方法如下:
setwd("/User/myname/./")
这个怎么样?
# 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 )
list.files
函数中的pattern
参数感兴趣。 - Rolandlist.dirs(recursive = FALSE)
(如果它们都在同一级别)。 - sebastian-csource
中加入chdir = T
。 - hadleysource
函数还有一个chdir
参数,它会临时将工作目录更改为源文件所在的目录。list.files
和/或其他工具创建一个包含每个脚本文件的文件名(包括路径)的向量。然后,使用source
函数分别对这些文件进行源代码处理,让source
和chdir
帮助您设置工作目录。for dir in /directoriesLocation/*/
do
cat $dir/scriptName.R | R --slave --args $arg1 $arg2
done
其中$dir是包含R脚本scriptName.R的所有目录的位置。