I am trying to write a function where it reads some pollution data from different files in a given directory, each file corresponding to records of a monitor and returns the mean value for one of the pollutants given as input argument to the function.
The data looks like this:
pollutantmean <- function(directory, pollutant, ID){
pmean <- 0
for (monitor in ID){
filename <- paste("./W2/", directory,"/", monitor,'.csv', sep = "")
print(filename)
pollution <- read.csv(file = filename, header = TRUE, sep = ",")
class(pollution)
head(pollution, n = 3)
pmean <- pmean + mean(pollution$pollutant, na.rm = TRUE)
}
return(pmean)
}
To run the function I set:
pollutantmean("specdata", "sulfate", 110:112)
I am getting the following output and error message:
[1] "./W2/specdata/110.csv"
[1] NA
Warning message:
In mean.default(pollution$pollutant, na.rm = TRUE) :
argument is not numeric or logical: returning NA
My questions are:
- How can I run the code line by line such that I see how the value of the local variables in the function changes? I looked up Youtube, but couldn't find a relevant video about it.
- When I copy-paste and run each line of the code in the function in console I see that the data is stored properly in the pollution data.frame. why can't I see the class and the head of the data.frame printed as output in the console? Instead I only get NA which is related to pmean I guess...
- How can I fix the error related to this error message?
question from:
https://stackoverflow.com/questions/66051706/debug-a-function-in-r-that-returns-na 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…