2016-09-16 3 views
1

目的はforループ内で現在の作業ディレクトリを変更し、それに他のものを入れます。ファイルを検索します。パスは汎用変数に格納されます。私はこのために実行している Rコードは以下の通りです:/foreachループのためにsetwd()へのパスの割り当てが遅れます

[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/" 
:私はこれを期待しているだろうが

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" 

です

したがって、current_dirに割り当てられたパスは、やや遅れていることが分かります...

これはなぜですか? 私はRエキスパートではないので、何がこの動作を引き起こしているのか、またどのように目的の動作を得るのかがわかりません。 どのようなヘルプ、ヒント、コードの修正/最適化が高く評価されるでしょう! ?setwdヘルプページから

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

答えて

2

...

setwdは目に見えないとgetwdと同じ規則で、変更前に、現在のディレクトリを返します。成功しなかった場合(実装されていない場合を含む)、エラーが発生します。

あなたは

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

を行うときにあなたが以前のものを得ている、「現在」のディレクトリを取得されていません。あなたが現在1

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

さて取得するgetwd()を使用する必要があり、それは間違ってどこに行くか、私は見ていないについて少しembaressed感じて知っている...しかし、おかげで迅速な啓蒙のためにたくさん! – rienix

関連する問題