samedi 10 novembre 2018

Beginner in R : writing my first function work only for one variable

I am a beginner in R. I am actually trying to code my first function.

I am looking for csv files in a directory on my computer, then I put them into a data frame and then I am asking for the mean of some variable.

I have 2 variable : sulfate and nitrate.

My function works fine for nitrate but not for sulfate. I really don't know what is wrong. R studio gave me a clue : In mean.default(directory$suftate, na.rm = TRUE) :

argument is not numeric or logical: returning NA

But I don't know what to do with this information.

My function is :

 pollutantmean <- function (directory, polluant = "nitrate", id = 1:332)
 directory <- data.frame()
 for (i in id)
{directory <- rbind(directory, read.csv(full_files[i]))} 
if (polluant == "nitrate"){
mean(directory$nitrate,na.rm = TRUE)} 
else if (polluant == "sulfate"){
mean(directory$suftate,na.rm = TRUE)}
else {print("KO")}
}

Can you help me ?

Caroline

Aucun commentaire:

Enregistrer un commentaire