Reputation:
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:
Upvotes: 0
Views: 120
Reputation: 2021
Good question. If you are using RStudio you can use the browser()
command to freeze the program at a certain spot so you can view the environment.
Be warned that it will stop every time you hit browser()
so you might need to put an if statement to detect a warning before running it. And don't forget to remove the statement once you're done.
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)
# Stop here and view the current environment
browser()
}
return(pmean)
}
Upvotes: 1