Argument is not numeric or boolean: return NA to R
I am trying to write a function to calculate the average of a column. The function has an argument directory and a column_name. However, I keep getting the error "argument is not numeric or boolean: return NA":
pollutantmean <- function(directory, pollutant) {
directoryVal <- directory
pollutantVal <- pollutant
pollutantData <- read.csv(directoryVal)
meanVal <- mean(pollutantData$pollutantVal, na.rm = TRUE)
}
I named it:
pollutantmean("001.csv", "nitrate")
"nitrate" is one of the column names.
Note that the following works, so I'm not sure why it doesn't work in my function:
mydata <- read.csv("001.csv")
mean(mydata$nitrate, na.rm = TRUE)
Please, help. Thank.
source to share
You should try meanVal <- mean(pollutantData[pollutantVal], na.rm = TRUE)
, in reality your dataframe pollutantData
doesn't have any call to the column pollutantVall
, so you have pollutantData$pollutantVal
which is NULL
. If you want to access a column of a data frame using a character, you must use square brackets.
source to share