I'm trying to create a simple function that will filter through my data frame and calculate means of either Ozone or PM while Site ID has a certain value. Data looks like this:
> dput(head(df))
structure(list(ozone = c(NA_real_, NA_real_, NA_real_, NA_real_,
NA_real_, NA_real_), pm = c(NA_real_, NA_real_, NA_real_, NA_real_,
NA_real_, NA_real_), site.id = c(1, 1, 1, 1, 1, 1)), row.names = c(NA,
6L), class = "data.frame")
My code is the following:
function1<-function(data, air_pollutant, site_id)
{
first_step<-subset(data, site_id)
pollution<-mean(first_step$air_pollutant, na.rm=TRUE)
pollution
}
However, when I try the following:
function1(dat_csv, ozone, 1:115)
It throws an error that
2: In mean.default(mean$air_pollutant, na.rm = TRUE): argument is not numeric or logical: returning NA
dput(my_input_data)
to the question, and make sure it is possible to reproduce the error you get on other machines using only the code and data provided in the question.?subset
reads, in part, "This is a convenience function intended for use interactively. For programming it is better to use the standard subsetting functions like [, and in particular the non-standard evaluation of argument subset can have unanticipated consequences." I don't know if that is your problem, but it is a bit of a red flag to be usingsubset
inside of a function definition like that.mean