【问题标题】:Why does function and conditional statements give wrong output?为什么函数和条件语句会给出错误的输出?
【发布时间】:2021-02-10 23:11:58
【问题描述】:

我创建了一个名为“salutation”的函数,它应该返回一个带有性别和名字变化的问候语。性别被定义为“M”或“F”。我尝试更改参数并将 x

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")

我的结果是“GreetingsMBailey,你今天好吗?”而不是“问候贝利先生,你今天好吗?”我输入的条件语句是否错误?

【问题讨论】:

    标签: r function conditional-statements


    【解决方案1】:

    试试这个。我将“sex”更改为“x”,因此您不只是返回用作函数输入的字符串。我还添加了一些空格以帮助易读性。

    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")
    

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 2019-09-01
    • 2020-12-24
    • 2020-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-30
    • 2016-09-29
    相关资源
    最近更新 更多