【问题标题】:How do I validate a user input for conditions using grepl如何使用 grepl 验证用户输入的条件
【发布时间】:2021-06-09 07:35:48
【问题描述】:

我试图坚持使用 base R 作为个人挑战。不过,我并不致力于使用 grepl,这只是我的第一个想法。我遇到了障碍。

这是我目前所拥有的:

armstrong <- function(x) {
if (grepl("^[-]{0,1}[0-9]{0,}.{0,1}[0-9]{1,}$", x) == FALSE) {
    stop("Please try submitting a valid number")
  } 
  else {
  temp <- strsplit(as.character(x), split = "")  
  y <- sapply(temp, function(y)sum(as.numeric(y)^length(y)))
  if (y == x) {
    print(paste("The number you entered,", x ,", is an Armstrong number"))
    }
  else {
    print(paste("The number you entered,", x ,", is not an Armstrong number"))
    }
  }
}

armstrong(readline(prompt = "Please enter a three digit positive number"))

程序检查用户是否输入了Armstrong number。那部分有效。我坚持的是用户输入的错误处理。如果用户输入负数,或者如果他们输入数字之间的字符,例如 1a4,我无法让 grepl 输出 FALSE。如果 grepl 输出 FALSE 就好了,因为用户输入的数字不是 3 位数,但这没什么大不了的,因为该函数仍然可以工作。

如何更新正则表达式以帮助处理错误?

【问题讨论】:

    标签: r error-handling user-input grepl


    【解决方案1】:

    为什么不直接

    if (! is.numeric(x) || x < 0) stop(…)
    

    换句话说:使用正确的类型。如果输入应该是数字,则不要接受字符串。

    如果您需要接受一个字符串,将该字符串转换为数字并测试转换是否成功。你可以测试NA是否成功。

    我还建议对该函数进行一些其他更改:

    armstrong <- function (x) {
      num <- as.numeric(x)
      if (is.na(num) || num < 0) stop("Please try submitting a valid number")
    
      digits <- strsplit(x, "")[[1L]]
      sum <- sum(as.numeric(digits) ^ length(digits))
      msg <- paste0(
        "The number you entered, ", x, ", is ",
        if (num != sum) "not " else "",
        "an Armstrong number"
      )
      message(msg)
    }
    

    【讨论】:

    • 这导致我所有的输入都是错误的。甚至像 153 这样的实际阿姆斯壮数字
    • @speakwiththepen 如果没有具体的代码和示例,就不可能诊断出这个问题。 armstrong(153) 对我的回答有所改变。
    • 问题来自用户提示。 armstrong(readline(prompt = "Please enter a three digit positive number")) 在控制台输入 153 会给出 stop() 消息
    • @speakwiththepen 请参考我回答的最后一句话。
    • @speakwiththepen 就是normal subsetting,获取第一个列表项。我使用 1L 而不是 1 更清楚地表明我正在使用 integer (在 R 中,1 是浮点数文字,然后 R 需要在可以用作子集索引之前在内部转换为整数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-26
    • 2016-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多