【问题标题】:Working Directories in R using for loopR中的工作目录使用for循环
【发布时间】:2017-01-19 06:39:19
【问题描述】:

我有一个要解压的 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),但这没有用。

【问题讨论】:

    标签: r directory subdirectory


    【解决方案1】:

    我认为使用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"
    

    【讨论】:

    • 谢谢老兄,它也对我有用。有什么理由不让我一开始就这样做吗?我的意思是是因为我是通过调用函数来赋值的吗??
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-13
    • 1970-01-01
    • 2016-01-18
    • 1970-01-01
    相关资源
    最近更新 更多