ab4444
ab4444

Reputation: 37

Why does function and conditional statements give wrong output?

I made a function called "salutation" that is supposed to return a greeting with a change in sex and name. Sex has been defined as "M" or "F". I've tried changing the parameters and adding x <- to the statements but I am not getting the result I want.

salutation <- function(sex, name){if (sex == "M"){x <- "Mr."} 
  else {if (sex == "F"){x <- "Ms."}}
   {paste0("Greetings", sex, name,", How are you today?")}
}


salutation("M","Bailey")

My result ends up being "GreetingsMBailey, How are you today?" instead of "Greetings Mr. Bailey, How are you today?" Am I entering the conditional statements wrong?

Upvotes: 0

Views: 25

Answers (1)

barleyguy
barleyguy

Reputation: 36

Give this a try. I changed "sex" to "x" so you don't just return the string you used as input for the function.. I've also added some spaces to help with legibility.

salutation <- function(sex, name){if (sex == "M"){x <- "Mr."} 
  else {if (sex == "F"){x <- "Ms."}}
   {paste0("Greetings ", x," ", name,", How are you today?")}
}

salutation("M","Bailey")

Upvotes: 1

Related Questions