0

I need a program that prints the numbers from 1 to 100. But for numbers that are multiples of three print Multipleof3 instead of the number and for the multiples of five print Multipleof5

p2<-function(x){
  x=c(1:100)
  if (x%%3==0){
  print ("Multipleof3")
  } else if (x%%5 == 0){
  print("Multipleof5")
  } else {
   print(x)
  }
  }

Thank you

Zar
  • 47
  • 1
  • 9

1 Answers1

2

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.

etienne
  • 3,648
  • 4
  • 23
  • 37