1

I have following code for getting the pollutant mean. The data for the program are in folder specdata with names "001.csv", "002.csv", ... to "332.csv" . The names of any one data gives following names:

[1] "Date"    "sulfate" "nitrate" "ID"  

In the code below, I have to calculate the mean of pollutant nitrate or sulfate . I think the code is correct. But data$pollutant is giving

NULL

Error in pollutantmean("specdata", "sulfate", 23) : attempt to apply non-function

The code is supposed to call in following way:

pollutantmean("specdata", "nitrate", 23)

What am I doing wrong here??

pollutantmean <- function(directory, pollutant, id = 1:332) {
  f <- function(num){
    if(num>=0 & num<=9){
      fname <- paste('specdata/00',as.character(num),".csv",sep="")
    }
    else if (num>=10 & num <=99){
      fname <- paste('specdata/0',as.character(num),".csv",sep="")
    }
    else{
      fname <- paste('specdata/',as.character(num),".csv",sep="")
    }
    data <- read.csv(fname)
    data <- data[complete.cases(data),]
    return(mean(data$pollutant))
  }
  results <- sapply(id, f)
  return(results)

}
thelatemail
  • 91,185
  • 12
  • 128
  • 188
Mahadeva
  • 1,584
  • 4
  • 23
  • 56

1 Answers1

0

The error you have is most probably caused by calling data$pollutant. You have pollutant="nitrate", which is a character string, in that case reference by $ is not going to work. Use [] instead, here's a minimal example:

df <- data.frame(hello=1:3, world=5)
name <- "hello"
df$name
NULL
df[name]
#  hello
#1     1
#2     2
#3     3
tonytonov
  • 25,060
  • 16
  • 82
  • 98
  • Thanks, this was the problem. But check that df$"hello" still gives the data. So, I was getting the confusion. – Mahadeva May 16 '14 at 06:20
  • Please tell me how df$"hello" gives the answer but df$name doesn't – Mahadeva May 16 '14 at 06:24
  • `df$name` is interpreted as "search column names for something like 'name'", so there is no actual lookup for variable `name`. See [this](http://stackoverflow.com/questions/18222286/select-a-specific-column-using-the-dollar-sign-in-r/18228613#18228613) answer for more details. – tonytonov May 16 '14 at 06:30