Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

How to shorten this \"if-else\" statements in R studio? Thank you sooo much! fiz

ID: 3783036 • Letter: H

Question

How to shorten this "if-else" statements in R studio? Thank you sooo much!

fizzbuzz = function(v = NULL){
for (term in v){
if (is.infinite(term) != TRUE){
if (is.numeric(term)){
if (term == as.integer(term)){
if (term %% 3 == 0){
if (term %% 5 == 0){
print("FizzBuzz")}
else {
print("Fizz")
}
}
else if (term %% 5 == 0){
print("Buzz")
}
else {
print(term)
}
}
else {
print ("This number is not an integer.")
}
}
else {
print ("This is not a number, or this number was entered as a string.")
}
}
else {
print ("You must enter an integer for this function to work.")
}
}
}

Explanation / Answer

fizzbuzz = function(v = NULL){
   for (term in v){
       if ((is.infinite(term) != TRUE) && is.numeric(term) && (term == as.integer(term))){
           if (term %% 3 == 0 && term %% 5 == 0){
               print("FizzBuzz")
           }
           else if (term %% 5 == 0){
               print("Buzz")
           }
           else if(term %% 3 == 0){
               print("Fizz")
           }
           else {
               print(term)
           }

       }
       else {
           print ("You must enter an integer for this function to work.")
           print ("This is not a number, or this number was entered as a string.")
       }
   }
}

Please let me know in case of any issue

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote