文件错误(文件,“rt”):无法打开连接 - 无法打开文件'specdata'访问被拒绝

时间:2015-02-19 02:07:55

标签: r rstudio read.csv

我在Windows 7上运行rStudio v3.1.2。这台笔记本电脑是一台64位计算机。

我正在参加Coursera提供的JHU R编程课程,并且遇到了我在第1部分问题中收到的错误。我有一些错误处理函数我不在这个例子中,所以我真的只是想展示我绝对需要的东西。我包含消息的唯一原因是证明必须满足所有条件才能继续。

  pollutantmean <- function(directory, pollutant, id=1:332) {

  setwd("C:\\Users\\WR-eSUB\\specdata")

  if(!isValidDirectory(directory)) {
        stop("Invalid input given.  Please specify valid directory to operate on.")
  }
  if(!isValidPollutant(pollutant)) {
        stop("Invalid input given.  Please specify valid pollutant (nitrate/sulfate).")
  }
  if(!isValidIdRange(id)) {
        stop("Invalid input given.  Please specify valid id range (1:332).")
  }
  sortedData = numeric()
  for (i in id) {
        thisFileName = paste(formatC(i, width = 3, flag = "0"), ".csv", sep="")
        thisFileRead = read.csv(directory, thisFileName)
        sortedData = c(sortedData, thisFileRead[[pollutant]])
  }
  mean(sortedData, na.rm = TRUE)
}

请注意,WR-eSUB内部是一个名为specdata的文件夹,在 文件夹中,有一个包含.csv文件的目录,也称为specdata。我可以改变这一点,但到目前为止,我一直在使用它,我没有遇到任何问题。

当我致电pollutantmean("specdata", "nitrate", 1:2)时,收到以下错误消息:

 Error in file(file, "rt") : cannot open the connection 
 In addition: Warning message: In file(file, "rt") : cannot open file 'specdata': Permission denied

现在,在我尝试完成这部分任务的众多尝试中,我已经能够使用像lapply这样的东西以其他方式提取数据,但因为我一直被卡住了,我把所有东西扔掉了,想要用这种方式尝试

我在网上搜索试图找到这个解决方案。尽管有几个回答的问题,但它们似乎都没有像这个一样令人困惑。 WR-eSUB是一个管理文件夹,但以前尝试在其中打开文件之前没有产生此错误。

3 个答案:

答案 0 :(得分:1)

此行将失败:

read.csv(directory, thisFileName)

因为,就?read.csv方向的粗略一瞥会告诉你,该函数的第一个参数是:

file: the name of the file which the data are to be read from.
      Each row of the table appears as one line of the file.  If it
      does not contain an _absolute_ path, the file name is
      _relative_ to the current working directory, ‘getwd()’.
      Tilde-expansion is performed where supported.  This can be a
      compressed file (see ‘file’).

并且您正在传递directory(如specdata所示,根据您显示的电话而定。)

鉴于setwd()已将您置于此目录中,不会

read.csv(theFileName)

工作?

答案 1 :(得分:1)

睡个好觉后,我看到了问题。我根本没有使用目录,所以我需要添加它。

thisFileName = paste(directory, "/", formatC(i, width = 3, flag = "0"), ".csv", sep="")

答案 2 :(得分:0)

我在2018年从Coursea学习R编程。我知道这个问题已经在3年前发布了但我还是希望发帖,如果有人想知道的话。

我在阅读this link后也面临同样的问题。

我发现我们需要指定文件夹的位置以及文件夹中的文件。所以我把代码放了:

folder<- "C:\\Users\\PHD\\Documents\\specdata"
file_list <- list.files(path=folder, pattern="*.csv")
相关问题