R for 循环仅适用于一个文件

R for loop works only for one file

我一直在尝试 运行 为 R 中的多个 csv 文件创建一个 for 循环。但是第一个文件的循环只有 运行s。

我想导入 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是初始设置的工作目录下的文件。但是由于我导入它们然后更改目录,我不明白为什么我一直收到第三条错误消息。

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

检查你的这行代码。

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

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