输入为字符串时R函数出错

时间:2016-10-29 19:01:54

标签: r function for-loop

我已经制作了一个函数,用于测试6和/或3的倍数范围内的哪些数字,或者没有数字。

Multi <- function(x,y) {
 z = x:y
 for (i in z) {
  if (i%%1!=0 | i<0) {
   print("Error!")
   break
 } else if (i%%3==0 & i%%6==0) { 
   print(paste(i, "is multiple of both 3 and 6"))
 } else if (i%%3==0) {
   print(paste(i, "is multiple of 3"))
 } else {
   print(paste(i, "is not multiple"))
  }
 }
}

循环按我的意愿工作,但在第一个if语句中,如果提供了字符/字符串,我还希望它能打印"Error!"。我在尝试Multi("Hello",10)时收到的消息是:

Error in x:y : NA/NaN argument In addition: Warning message: In Multi("Hello", 10) : NAs introduced by coercion

我尝试了suppressWarnings()功能,但我无法使其正常工作。

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

试试这个:

Multi <- function(x,y) {
  if (!is.numeric(x) | !is.numeric(y)) {
    print("Error!")
  } else {
    z = x:y
    for (i in z) {
      if (i%%1!=0 | i<0) {
        print("Error!")
        break
      } else if (i%%3==0 & i%%6==0) { 
        print(paste(i, "is multiple of both 3 and 6"))
      } else if (i%%3==0) {
        print(paste(i, "is multiple of 3"))
      } else {
        print(paste(i, "is not multiple"))
      }
    }
  }
}
Multi(1,10)
Multi('Hello', 10) # now it will print Error without a NaN: 'Hello':10 was causing this NaN

您可以稍微减少代码

sapply(1:10, function(i) ifelse(i%%3==0, 
                                ifelse(i%%6==0, 
                                       paste(i, "is multiple of both 3 and 6"), 
                                       paste(i, "is multiple of 3")),
                                paste(i, "is not multiple")))