r - R 中使用 for 循环的工作目录

标签 r directory subdirectory

我有一个正在解压的 zip 文件,然后我使用 for 循环遍历工作目录中的目录,然后将工作目录更改为我刚刚解压的新文件夹。不过,好像不太喜欢。

下面是我使用过的两个代码,其中一个最终出现错误,而第二个则没有执行我想要的操作。我想我可能混合了一些 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 成为工作目录,以便我可以循环遍历文件,但它不喜欢它。

我在浏览 Stackoverflow 上的一些页面后尝试的第二个代码是使用 Paste0() 修改为下面的,该代码一直有效,但随后出现错误:

> 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"

因此,正如您在第二个代码中看到的那样,它跳转到该文件夹​​,但抛出错误消息。我也尝试过简单地使用 path.expand(i) 但这不起作用。

最佳答案

我认为使用 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 返回更改之前的当前目录”。 (感谢@Tensibai。)请参阅以下示例:

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

关于r - R 中使用 for 循环的工作目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39439912/

相关文章:

php - sql - 查找哪个文件夹未使用

java - 写入 Zip 中的子目录?使用 java.util.zip。 ZipEntry.putNextEntry()

C 使用 stat 获取文件名、大小和权限

R:在 ggplot2 中绘制线性判别分析的后验分类概率

r - 如何从 dplyr 中的 case_when 捕获逻辑

r - 如何在 R 中使用相同的种子在并行或不并行的情况下产生相同的输出?

c++ - 结构声明范围

r - 如何更改警告设置?

c - 在C程序中查找目录

Cmake - 如何构建在不同子文件夹中分开的项目