简体   繁体   English

当前工作目录中的setwd()

[英]setwd() in the current working dir

I have a list of folders. 我有一个文件夹列表。 In each folder there's an R identical script that have to run on files into the folder. 在每个文件夹中都有一个R相同的脚本,必须在文件夹上运行文件。 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. 问题是我有一个大约100个文件夹的列表,因此我不可能手动设置当前工作目录中的setwd()。 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. 或以另一种简单的方式告诉R当前工作目录,而不是每次键入文件夹名称。

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. 据我所知,您希望触发一批R脚本,其中脚本分布在多个文件夹中。

Personally, I would probably write a shell script (or OS equivilent) to do this, rather than doing it in R. 就个人而言,我可能会编写一个shell脚本(或OS等效)来执行此操作,而不是在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 其中$ dir是包含R脚本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. 除了其他很好的答案之外, source函数还有一个chdir参数,它会暂时将工作目录更改为源文件所在的目录。

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. 一种选择是使用list.files和/或其他工具为每个脚本文件创建包含文件名(包括路径)的向量。 Then source each of those files and letting source with chdir handle setting the working directory for you. 然后, source每个这些文件,并让sourcechdir手柄设置工作目录为您服务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM