0

I am quite new to the R area. During an assignment "Air pollution" in Coursera, I tried to write a function that returned the mean to the accumulated dataset.

  file <- list.files(directory, full.names= TRUE)
  data <- data.frame()
  for(val in id) {
  data <- rbind(data, read.csv(file[val]))
  }
  mean(data[[pollutant]], na.rm = TRUE)
}
    
pollutantmean("specdata", "sulfate", 1:20)

And I got the answer 3.016321, which was right. However, when I changed the subset code to mean(data$pollutant, na.rm = TRUE This returned an error Error in <my code> : object of type 'closure' is not subsettable Why did this happen? And is there possibly a correct way to subset the data using $ in this code? I tried to search for the answer for myself but still could not figure out the solution. Thank you for your kind answer.

Pete Kittinun
  • 593
  • 3
  • 15
  • You cannot subset in function using `$`. See https://stackoverflow.com/questions/18222286/dynamically-select-data-frame-columns-using-and-a-character-value Also for your function `pollutantmean` there are lot of posts on SO regarding this. See https://stackoverflow.com/search?q=%5Br%5D+pollutantmean – Ronak Shah Dec 04 '20 at 07:26
  • Thanks for your kind help and your suggestion on the comment in asking questions! – Pete Kittinun Dec 04 '20 at 08:03

0 Answers0