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

我在
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.我可以改变这一点,但到目前为止,我一直在使用它,我没有遇到任何问题.

当我调用污染物(“specdata”,“硝酸盐”,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是一个管理文件夹,但之前尝试打开其中的文件之前没有产生此错误.

最佳答案 这一行将失败:

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’).

并且您将目录传递给它(如您显示的调用中的specdata).

鉴于setwd()已经将你放在这个目录中,不会

read.csv(theFileName)

工作?

点赞