【问题标题】:R for loop works only for one fileR for 循环仅适用于一个文件
【发布时间】:2015-11-12 20:06:40
【问题描述】:

我一直在尝试为 R 中的多个 csv 文件运行 for 循环。但该循环仅对第一个文件运行。

我想导入 csv 文件,然后为每个 csv 文件创建一个目录,用于存储其数据分析。创建目录后,每次运行代码时都无法将其设置为工作目录。我的代码在只有一个文件时可以正常工作,但在我使用 for 循环时会失败。

代码:

## Setting the working directory and path
setwd("path")
path <- "path"

##to extract the filename from each path
files <- list.files(path=path, pattern="*.csv")
for(file in files)
{
  temp <- which(strsplit(file, "")[[1]]==".")
  assign(
    gsub(" ","",substr(file, 1, temp-1)), 
    read.csv(paste(path,file,sep="")))
}

##To create a new directory for each file and set that as the new working directory.

    for(i in seq(1, length(files), by = 1)){
      fileName <- read.csv(files[i])
      base <- strsplit(files[i], ".csv")[[1]]
      dir <- dir.create(paste(path,base, sep = "/"))
      setwd(getwd(dir))

将结果存储在新设置的工作目录中进行进一步分析。

创建变量

Date_Time <- strptime(fileName$Date...Time, format = "%d/%m/%Y %H:%M")
  fileName$month <- months(Date_Time,abbreviate = TRUE)  #creates month column (char)
  fileName$julian <- Date_Time$yday  #creates julian day column
  fileName$year <- Date_Time$year + 1900  #creates year column
  fileName$hour <- Date_Time$hour  #creates hour column
  fileName$weeknum <- round(Date_Time$yday/7,0)
  fileName$numericdate <- fileName$year+fileName$julian/366  #numeric value of date

  #Identify and remove empty columns
  fileName <- as.data.table(fileName)
  fileName <- fileName[,which(unlist(lapply(fileName, function(x)!all(is.na(x))))),with=F]
  dim(fileName) # to check if empty columns have been eliminated
  head(fileName) #to find appropriate column name for PM10 data
  PM10 <- fileName$PM10_BAM #substitue in a common variable for further calculations
  fileName$PM10_BAM <- as.numeric(as.character(PM10))

  ##to view basic seasonal pattern through the data
  df_eve <- subset(fileName, hour>=18)
  jpeg(file = "seasonal pattern observed in the evenings.jpg")
  with(df_eve, boxplot(PM10_BAM ~ weeknum, main = "seasonal pattern observed in the evenings", xlab = "weeknum", ylab = "PM10", outline = FALSE, na.rm = T))
  dev.off()
}


Errors:

Error in file(file, "rt") : cannot open the connection In addition: Warning messages:
1: In dir.create(paste(path, base, sep = "/")) :
  '/Users/ayushikachhara/Desktop/Work/CSV//EW_Matamata' already exists
2: NAs introduced by coercion 
3: In file(file, "rt") :
  cannot open file 'EW_Ngaruawahia.csv': No such file or directory

EW_Matamata 和 EW_Ngaruawahia 是最初设置的工作目录中的文件。但是由于我导入它们然后更改目录,我不明白为什么我不断收到第三条错误消息。

感谢任何帮助,因为我正处于学习阶段:)

【问题讨论】:

    标签: r for-loop setwd


    【解决方案1】:

    检查这行代码。

          dir <- dir.create(paste(path,base, sep = "/"))
          setwd(getwd(dir))
    

    现在,当它获取第一个文件时,它会创建一个新目录并将工作目录设置为新创建的目录的目录。因此,当它在当前目录中查找第二个文件时,它显然不存在

    【讨论】:

    • 嘿,谢谢!那行得通。我意识到这是一个愚蠢的问题,我被困了好几个小时!我还将我的 csv 文件保存在另一个文件夹中,并且在将新目录设置为工作目录后,它迷路了。通过在退出循环之前将初始目录设置为工作目录来解决此问题..
    • wc :) ,我们似乎总是卡在琐碎的事情上。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    • 2017-08-22
    • 2018-08-31
    • 2018-03-13
    • 1970-01-01
    相关资源
    最近更新 更多