当前工作目录中的setwd()

时间:2013-02-22 14:30:31

标签: r

我有一个文件夹列表。在每个文件夹中都有一个R相同的脚本,必须在文件夹上运行文件。我编写了一次脚本并将脚本复制到每个文件夹中。问题是我有一个大约100个文件夹的列表,因此我不可能手动设置当前工作目录中的setwd()。我想知道是否可以设置当前工作目录,例如“。”这样:

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

或以另一种简单的方式告诉R当前工作目录,而不是每次都输入文件夹名称。

3 个答案:

答案 0 :(得分:7)

怎么样?

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

答案 1 :(得分:3)

据我了解,您希望触发一批R脚本,其中脚本分布在多个文件夹中。

就个人而言,我可能会编写一个shell脚本(或操作系统等效)来执行此操作,而不是在R中执行。

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

其中 $ dir 是包含R脚本 scriptName.R

的所有目录的位置

答案 2 :(得分:3)

除了其他很好的答案之外,source函数还有一个chdir参数,它会暂时将工作目录更改为源文件所在的目录。

一种选择是使用list.files和/或其他工具为每个脚本文件创建包含文件名(包括路径)的向量。然后source每个文件,让source chdir处理为您设置工作目录。

相关问题