2016-09-11 13 views
3

私は解凍しているzipファイルを持っていますが、私はforループを使用して作業ディレクトリのディレクトリを移動し、作業ディレクトリを開かれたばかりの新しいフォルダに変更します。しかし、それはそれを好きではないようです。Rのforループを使用している作業ディレクトリ

以下は私が使用している2つのコードですが、そのうちの1つはエラーで終了しますが、2つ目のコードは私がしたいことをしません。私はおそらくいくつかのPythonロジックを混ぜていると思いますか?

for (i in list.files("./")){ 
    if (endsWith(tolower(i),"zip")){ 
    unzip(i) 
    cat("Unzipped",i,"\n") 
    } 
} 

for (i in list.dirs(getwd())){ 
    cat("This is i",i,"\n") 
    Root <- setwd(i) 
    cat("This is ROOT",Root,"\n") 

} 

print(Root) 

次のように私は上記のコードを実行しているから得る結果は次のとおりです。

This is i F:/Testing with R 
This is ROOT F:/Testing with R 
This is i F:/Testing with R/ABC_Data 
This is ROOT F:/Testing with R 

あなたが見ることができるように、私はフォルダをループにそれを好きとABC_Dataになるだろう作業ディレクトリようにIファイルをループすることができますが、それは好きではありません。することができますように、そう

> for (i in list.files("./")){ 
+ if (endsWith(tolower(i),"zip")){ 
+  unzip(i) 
+  cat("Unzipped",i,"\n") 
+ } 
+ } 
Unzipped GVA_BillData.zip 
> 
> for (i in list.dirs(getwd())){ 
+  cat("This is i",i,"\n") 
+  Root <- paste0(path.expand(i),"/") 
+  cat("This is ROOT",Root,"\n") 
+ 
+ } 
This is i F:/Testing with R 
This is ROOT F:/Testing with R/ 
This is i F:/Testing with R/ABC_Data 
This is ROOT F:/Testing with R/ABC_Data/ 
> 
> print(Root) 
[1] "F:/Testing with R/ABC_Data/" 
> 
> File_count <- 0 
> for (a in list.files(Root)){ 
+ print(a) 
+ if (endsWith(tolower(a),"csv")){ 
+  if (length(grep("service file",tolower(a)) > 0)){ 
+  Import <- read.csv(a, header = TRUE) 
+  for (i in 1:nrow(Import)){ 
+   Import_Date <- Import[1,4] 
+   if (File_count == 0){ 
+   write.table(c(Import[i,],Import_Date,a),"Output.csv",append = TRUE,sep = ",",row.names = FALSE,col.names = TRUE) 
+   File_count <- File_count + 1 
+   } else (write.table(c(Import[i,],Import_Date,a),"Output.csv",append = TRUE,sep = ",",row.names = FALSE,col.names = FALSE)) 
+   } 
+   } 
+  } 
+ } 
[1] "1234_126311.csv" 
[1] "Service File.csv" 
Error in file(file, "rt") : cannot open the connection 
In addition: Warning message: 
In file(file, "rt") : 
    cannot open file 'Service File.csv': No such file or directory 
> print("Finished") 
[1] "Finished" 

:私は、ある時点まで働い以下にpaste0()を使用して、改正されたのStackOverflow上の一部のページを経由した後にしようとしたが、第2のコードがエラーを与えた

2番目のコードでは、フォルダにジャンプしますが、エラーメッセージをスローします。私は単純に path.expand(i)を使ってみましたが、うまくいきませんでした。

答えて

2

setwd()を使用すると割り当てが問題の原因だと思います。最初に次のコードに調整してください:

for (i in list.dirs(getwd())){ 
    cat("This is i",i,"\n") 
    setwd(i) 
    Root <- getwd() 
    cat("This is ROOT",Root,"\n")  
} 

私にとってはうまくいくようです。

問題は、setwd()が機能していないということではなく、割り当てが古い作業ディレクトリを返すことです。ドキュメント(?setwd)は、 "setwdが変更前のカレントディレクトリを返す"と言っています。 (ありがとう@天気台)次の例を参照してください。

setwd("c:/") 
getwd() 
# [1] "c:/" 
z<-setwd("c:/Users/") 
z 
# [1] "c:/" 
getwd() 
# [1] "c:/Users" 
+0

ありがとう、それは私のためにも働いた。 私が最初にそれをさせてくれなかった理由は何ですか?私は関数を呼び出すことによって値を割り当てていたので、それは意味ですか? – AmarKahlon

関連する問題