对于/ foreach循环,setwd()的路径分配被延迟

时间:2016-09-16 15:43:03

标签: r setwd

目标是在for循环中更改当前工作目录并在其中执行其他一些操作,例如。搜索文件。路径存储在通用变量中。 我为此运行的R代码如下:

require("foreach")

# The following lines are generated by an external tool and stored in filePath.info 
# Loaded via source("filePaths.info")
result1 <- '/home/user/folder1' 
result2 <- '/home/user/folder2'
result3 <- '/home/user/folder3' 
number_results <- 3

# So I know that I have all in all 3 folders with results by number_results 
# and that the variable name that contains the path to the results is generic: 
# string "result" plus 1:number_results.

# Now I want to switch to each result path and do some computation within each folder
start_dir <- getwd()
print(paste0("start_dir: ",start_dir))

# For every result folder switch into the directory of the folder
foreach(i=1:number_results) %do% { 
# for (i in 1:number_results){ leads to the same output

    # Assign path in variable, not the variable name as string: current_variable <- result1 (not string "result1")
    current_variable <- eval(parse(text = paste0("result", i)))
    print(paste0(current_variable, " in interation_", i))
    # Set working directory to string in variable current_variable
    current_dir <- setwd(current_variable)
    print(paste0("current_dir: ",current_dir))

    # DO SOME OTHER STUFF WITH FILES IN THE CURRENT FOLDER
}

# Switch back into original directory
current_dir <- setwd(start_dir)
print(paste0("end_dir: ",current_dir))

输出如下......

[1] "start_dir: /home/user"
[1] "/home/user/folder1 in interation_1"
[1] "current_dir: /home/user"
[1] "/home/user/folder2 in interation_2"
[1] "current_dir: /home/user/folder1"
[1] "/home/user/folder3 in interation_3"
[1] "current_dir: /home/user/folder2"
[1] "end_dir: /home/user/folder3"

......虽然我原本预料到了这一点:

[1] "start_dir: /home/user"
[1] "/home/user/folder1 in interation_1"
[1] "current_dir: /home/user/folder1"
[1] "/home/user/folder2 in interation_2"
[1] "current_dir: /home/user/folder2"
[1] "/home/user/folder3 in interation_3"
[1] "current_dir: /home/user/folder3"
[1] "end_dir: /home/user/"

事实证明,分配给current_dir的路径有点“落后”...

为什么会这样? 由于我远不是R专家,我不知道是什么导致了这种行为,最重要的是如何获得所需的行为。 所以任何帮助,提示,代码更正/优化都将受到高度赞赏!

R version 3.3.1 (2016-06-21) -- "Bug in Your Hair"
Platform: x86_64-pc-linux-gnu (64-bit)

1 个答案:

答案 0 :(得分:2)

来自?setwd帮助页面...

  

setwd在更改前返回当前目录,不可见且具有与getwd相同的约定。如果不成功(包括未实现),则会出错。

所以当你这样做时

current_dir <- setwd(current_variable)
print(paste0("current_dir: ",current_dir))

你没有得到&#34;当前&#34;目录,你得到的是前一个。您应该使用getwd()来获取当前的

setwd(current_variable)
current_dir <- getwd()
print(paste0("current_dir: ",current_dir))