[英]Error in file(file, “rt”) : cannot open the connection in r
I am new to programming.Currently doing R programming in coursera and got this error while doing assignment named "pollutantmean".I searched in forums and stackoverflow,but couldnt able to fix it.Appreciate your help.Thanks.我是编程新手。目前正在 coursera 中进行 R 编程,并在执行名为“pollutantmean”的作业时遇到此错误。我在论坛和 stackoverflow 中搜索过,但无法修复它。感谢您的帮助。谢谢。
I got this error :我收到此错误:
Error in file(file, "rt") : cannot open the connection In addition: Warning message:
In file(file, "rt") : cannot open file 'NA': No such file or directory
Note: I have a folder "specdata" which is the working directory.This "specdata" has all the 332 csv files.I want to calculate mean for one of the pollutant column named "pollutant" in those files and "directory" is the location of those files."id" is a integer vector mentioning the monitor number.so,here is my code:注意:我有一个文件夹“specdata”,它是工作目录。这个“specdata”包含所有 332 个 csv 文件。我想计算这些文件中名为“污染物”的污染物列之一的平均值,“目录”是这些文件的位置。“id”是一个整数向量,提到了监视器编号。所以,这是我的代码:
pollutantmean <- function(directory, pollutant, id = 1:332) {
files_full <- list.files(directory, full.names = TRUE)
dat <- data.frame()
for (i in id) {
dat <- rbind(dat, read.csv(files_full[i]))
}
mean(dat[, pollutant], na.rm = TRUE)
}
pollutantmean("specdata","sulfate",id = 1:10)
As per the error, it seems that list.files is returning empty vector for files names.根据错误,似乎 list.files 正在返回文件名的空向量。
list.files returns only file nam inside the directory by default. list.files默认只返回目录内的文件名。 So in that case, you should set the working directory first, so that read.csv will read the files inside the working directory.
所以在这种情况下,你应该先设置工作目录,这样 read.csv 将读取工作目录中的文件。
setwd("<directory name>")
Now your function should work fine.现在你的函数应该可以正常工作了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.