gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:37:50 24 4
gpt4 key购买 nike

我有一个正在解压的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com