Try :
p2<-function(x){
if (x%%3==0){
return ("Multipleof3")
} else if (x%%5 == 0){
return("Multipleof5")
} else {
return(x)
}
}
p<-Vectorize(p2)
p(1:100)
# [1] "1" "2" "Multipleof3" "4" "Multipleof5" "Multipleof3" "7" "8"
Note : you can replace p2
by :
p2<-function(x){
return(ifelse(x%%3==0, "Multipleof3", ifelse(x%%5==0, "Multipleof5", x)))
}
Your function parameter should not be in the question but defined like this : function(x)
and when you call the function you put your parameter (1:100
) at the place of x
. The Vectorize
allow to create a new function : p
which is the same as p2
but which is capable of handling vectors.
Use :
p2<-function(x){
return(ifelse(x%%3==0 & x%%5==0, "MultipleOfBoth", ifelse(x%%3==0, "Multipleof3", ifelse(x%%5==0, "Multipleof5", x))))
}
for handling multiple of 3 and 5.