To learn how to create functions, I am trying to make one that calculates averages, with three different error codes. However, I get two different error messages when running this code.
If i try avg(5), that is of just one number, I get "argument "no" is missing, with no default". And when trying avg("f"), so of something that is not a number I get the error: " multi-argument returns are not permitted" . What I want is for it to state it need several numbers if just one is given, and that the argument must be numerical if a character is given. I do belive the second problem could be solved by some kind of "Halt" commmand, however my (probably horrible) googling hasn't lead me to anything such as that. Appreciate all help, and thanks in advance!
avg <- function(x){
ifelse(class(x) == "numeric" & length(x)>1,
return(sum(x)/length(x)),
ifelse(class(x)!= "numeric",
return("Need to be numeric",
ifelse(length(x) <= 1,
return("Need more than one number"),
return("Unknown error")))))
}
Aucun commentaire:
Enregistrer un commentaire