argument is not numeric or logical: returning NA in R
Solution 1
You should try meanVal <- mean(pollutantData[pollutantVal], na.rm = TRUE)
, indeed your data frame pollutantData
doesn't have any column call pollutantVall
, so you have pollutantData$pollutantVal
which is NULL
. If you wan to access to a data frame column using a character, you have to use the square brackets.
Solution 2
I'd like to add a correction. It should actually be
meanVal <- mean(pollutantData[,pollutantVal], na.rm = TRUE)
Note the ,
before the pollutantVal
since pollutantVal
is a column and needs to be indexed as such.
Trung Tran
Updated on July 16, 2022Comments
-
Trung Tran almost 2 years
I am trying to write a function to calculate the mean of a column. The function has the arguments directory and column_name. However, I keep getting the error "argument is not numeric or logical: returning NA":
pollutantmean <- function(directory, pollutant) { directoryVal <- directory pollutantVal <- pollutant pollutantData <- read.csv(directoryVal) meanVal <- mean(pollutantData$pollutantVal, na.rm = TRUE) }
I called it by:
pollutantmean("001.csv", "nitrate")
"nitrate" is one of the column names.
Note that the following works, so I'm not sure why it's not working in my function:
mydata <- read.csv("001.csv") mean(mydata$nitrate, na.rm = TRUE)
Please help. Thank you.