【问题标题】:R function that produces "invalid" for text/character variable为文本/字符变量产生“无效”的 R 函数
【发布时间】:2019-04-27 02:21:03
【问题描述】:

我正在尝试在 R 中创建一个函数,如果整数大于 100,则输出“通过”,如果小于 100,则输出“失败”,如果等于 100,则输出“中性”。代码应显示“无效”对于字符变量/文本。

这是我目前的代码:

compare <- function(x) {

 if (x>100) {
  result = "pass"
 }

 else if (x<100) {
 result = "fail"
 }

 else if (x==100) {
 result = "neutral"
 }

 else if (is.character(x) == TRUE) {
 result = "invalid"
 }

 print(result)

 }

compare(10)
compare(100)
compare(120)
compare("text")

我希望 compare(10) 产生“失败”,compare(100) 产生“中性”,compare(120) 产生“通过”,比较 (“text”) 产生“无效”。所有整数都有效,但是 compare("text") 不断产生“通过”而不是“无效”。 Compare(as.character("text")) 也只产生“pass”。

【问题讨论】:

    标签: r function compare


    【解决方案1】:

    要创建条件语句,您需要== 而不是=

    compare <- function(x) {
      if (!is.numeric(x)) {
        result = "invalid"
      } else  if (x>100) {
        result = "pass"
      } else if (x<100) {
        result = "fail"
      } else if (x==100) {
        result = "neutral"
      } 
    
      print(result)
    }
    

    这个功能对我有用。以下是输出测试。

    > compare(10)
    [1] "fail"
    > compare(100)
    [1] "neutral"
    > compare(120)
    [1] "pass"
    > compare("hello")
    [1] "invalid"
    

    【讨论】:

    • 谢谢,但是当我尝试针对上述问题调整您的代码时,它不起作用(我也尝试使用 as.integer)。我重新发布了上面的完整问题。
    • compare &lt;- function(x) { if (!is.numeric(x)) { result = "invalid" } else if (x&gt;100) { result = "pass" } else if (x&lt;100) { result = "fail" } else if (x==100) { result = "neutral" } print(result) } 老实说,我不是 100% 确定似乎需要在第一个写 if (!is.numeric(x)) { result = "invalid" }
    猜你喜欢
    • 2020-03-04
    • 1970-01-01
    • 2011-10-25
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多