R编程:空气污染 - 污染物平均值

时间:2015-11-09 23:18:46

标签: r csv multiple-files

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

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

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

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

作业第1部分:

编写一个名为'pollutantmean'的函数,用于计算指定监视器列表中污染物(硫酸盐或硝酸盐)的平均值。函数'pollutantmean'有三个参数:'目录','污染物'和'id'。给定矢量监视器ID号,'pollutantmean'读取监视来自'directory'参数中指定的目录的颗粒物质数据,并返回所有监视器中污染物的平均值,忽略编码为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)之外的所有文件,其中扫描错误(文件,内容,nmax,sep,dec) ,引用,跳过,nlines,na.strings,:第1行没有7个元素 当我尝试sapply(filelist,read.csv)出现相同的错误。当我对“specdata”使用read.csv,sapply或lapply时,错误是 read.table中的错误(file = file,header = header,sep = sep,quote = quote,:输入中没有可用行< / strong>虽然我在“specdata”文件中包含了所有332.csv文件。

我希望我发布了可重复锻炼所需的一切。如果还有其他需要,请告诉我。

谢谢!

1 个答案:

答案 0 :(得分:0)

您似乎需要将目录设置为:

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

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