2016-09-16 50 views
1

目標是在for循環中更改當前的工作目錄,並在其中執行其他一些操作,例如.e.g。搜索文件。路徑存儲在通用變量中。 我這運行將R代碼如下:setwd()的路徑分配在for/foreach循環中被延遲

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) 

回答

2

?setwd幫助頁面...

setwd返回當前目錄中的更改之前,無形中並用相同的約定getwd。如果它不成功(如果沒有實現),它會發出錯誤。

所以,當你做

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

你沒有得到「當前」目錄下,你所得到的前一個。您應該使用getwd()來獲取當前一個

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

好了,知道我感到有點embaressed約沒看到哪裏出了問題...但非常感謝您的快速啓示! – rienix