如何修复-文件错误(文件,“ rt”):无法打开连接

问题描述 投票:0回答:1

在此代码中,我试图对ID值和某些if if语句使用for循环,因为这些文件的格式分别为“ 001.csv”,“ form”和“ 010”,所以我编写了此代码。计划是存储一个字符向量,然后使用read.csv读取它。我使用getwd()函数获取工作目录,然后使用setwd将其设置为相同目录,但仍然无法正常工作。所以基本上打破了1和10的循环,我试图形成此功能,主要问题是读取此文件。

Error in file(file, "rt") : cannot open the connection

是它向我展示的。我使用Windows 10和Rstudio。如果您需要更多详细信息,可以问我我将尽快答复,我们将不胜感激,

pollutmean <- function(pollutant="sulfate", id=1:332) {
  for (i in id) {
    if (i < 10) {
      x <- i
      char <- as.character(x)
      a <- paste("C:/Users/ksart/Desktop/Specdata/Specdata/00", char, ".csv",
                 sep="")  # this is where i m trying to read in the values
      temp1 <- read.csv(a)
      data_1 <- rbind.data.frame(data_1, temp1)
      data_1
    }      
    else if (10 <= i && i < 100 ) {  # for 10s files
      y <- i
      char1 <- as.character(y)
      b <- paste("C:/Users/ksart/Desktop/Specdata/Specdata/0", char1, ".csv",
                 sep="")
r file error-handling read.csv
1个回答
0
投票

这不是一个实际的答案,只是一些简化上面代码的建议(不能格式化注释中的代码)。还更正了rbind.data.frame的问题。

pollutmean <- function(pollutant="sulfate", id=1:332) {
  # to make rbind.data.frame work below, you have to create an initial 
  # empty dataframe (col1=integer() is just an example, use your 
  # column names and data types, see
  # https://stackoverflow.com/questions/10689055/create-an-empty-data-frame
  # for details)
  # another option is to create the data.frame from the first file,
  # and only rbind the latter ones
  data <- data.frame(col1=integer(), ...)

  for (i in id) {
    num_as_char <- as.character(i)
    if (i < 10) {
      file_name <- paste("C:/Users/ksart/Desktop/Specdata/Specdata/00",
                         num_as_char, ".csv", sep="")
    } else if (i < 100) {
      file_name <- paste("C:/Users/ksart/Desktop/Specdata/Specdata/0",
                         num_as_char, ".csv", sep="")
    } else {
      file_name <- paste("C:/Users/ksart/Desktop/Specdata/Specdata/",
                         num_as_char, ".csv", sep="")
    }
    temp <- read.csv(file_name)
    data <- rbind.data.frame(data, temp)
  }

  data
}
© www.soinside.com 2019 - 2024. All rights reserved.