R程序设计:空气污染-污染物平均值



这是我第一次尝试在R中导入多个CSV文件,并使用一些CSV文件来计算硫酸盐和硝酸盐的平均值来解决这部分任务。我在stackoverflow和其他网站上搜索了答案,但我无法根据问题中关于该主题的内容来解决这个问题。我也是R编程的新手。

如果有用:R版本为3.2.1Mac OS X 10.7.5版

我在Coursera有一个作业,我有332个CSV文件,我必须计算污染物的平均值。

下载文件的链接:https://d396qusza40orc.cloudfront.net/rprog%2Fdata%2Fspecdata.zip

任务第1部分:

编写一个名为"污染物平均值"的函数,计算指定监测器列表中污染物(硫酸盐或硝酸盐)的平均值。"函数"curlatentmean"接受三个参数:"directory"、"pollution"one_answers"id"。"。给定矢量监测器ID号,"污染平均值"从"目录"参数中指定的目录中读取监测器的颗粒物数据,并返回所有监测器的污染物平均值,忽略任何编码为NA的缺失值。

函数原型:

pollutantmean <- function(directory, pollutant, id = 1:332) {
## 'directory' is a character vector of length 1 indicating
## the location of the CSV files
## 'pollutant' is a character vector of length 1 indicating
## the name of the pollutant for which we will calculate the
## mean; either "sulfate" or "nitrate".
## 'id' is an integer vector indicating the monitor ID numbers
## to be used
## Return the mean of the pollutant across all monitors list
## in the 'id' vector (ignoring NA values)

我的结果应该是:

source("pollutantmean.R")
pollutantmean("specdata", "sulfate", 1:10)
## [1] 4.064
pollutantmean("specdata", "nitrate", 70:72)
## [1] 1.706
pollutantmean("specdata", "nitrate", 23)
## [1] 1.281

我已经创建了我的工作目录,这是因为我无法更进一步。

> setwd("~/Desktop/Coursera /R_Prog")
> getwd()
[1] "/Users/amandamariamcharpinel/Desktop/Coursera /R_Prog"
> dir()
[1] "specdata"     "specdata.zip"
> directory <- "specdata"
> filelist <- list.files(directory, full.names=TRUE)
> pollutantmean<-function(directory, pollutant, id=1:332)

每当我尝试使用F1&lt-read.csv("文件名",header=TRUE)出现的错误是文件中的错误(文件,"rt"):不可能打开连接另外:警告消息:文件中(文件,"rt"):不可以打开文件'nameoffile.csv':没有这样的文件或目录当我使用命令read.table(filechoose(),header=TRUE)时,它适用于除第一个文件(001.csv)外的所有文件,该文件显示扫描错误(file,what,nmax,sep,dec,quote,skip,nlines,na.strings,:第1行没有7个元素当我尝试sapply(filelist,read.csv)时,会出现同样的错误。当我使用read.csv、sapply或lapply作为"specdata"时,错误为read.table中的错误(file=file,header=header,sep=sep,quote=quote,:输入中没有可用的行,尽管我在"specdata"文件中有所有332.csv文件。

我希望我发布了一个可重复练习所需的一切。如果还有什么需要的,请告诉我。

谢谢!

看起来您需要将目录设置为:

directory<-"/Users/amandamariamcharpinel/Desktop/Coursera /R_Prog/specdata"

由于文件位于specdata文件夹中,因此需要通过完整的文件路径指向r。

最新更新