【问题标题】:How do I return to a certain line or argument in a function in R?如何返回 R 函数中的特定行或参数?
【发布时间】:2017-05-03 17:24:47
【问题描述】:

我有一个根据用户输入验证 url 的函数。设置函数的方式,如果 url 不验证(因为它不存在或因为它是重复的),函数就会结束。

如何做到这一点,如果 url 未验证,用户返回输入对话框以重新开始验证过程,而不是仅仅结束函数?

exfun <- function(){
x <- toupper(readline("Do you want to do the function? Y/N......."))
if (x == "Y"){
writeLines("This is where the function body would be, but it's huge so for the sake of this StackExchange question, we'll just make it a simple thing")
} else 
writeLines("Well then why did you start the function? We'll try this again")
#This is where I would like the function to return to the "x<-...." line.

有几个地方我希望能够“返回 X 行”,因为至少有两个验证点。我将它设置为一系列if else 参数,else 成为一条消息。如何将else 变成消息并让用户回到开始/之前的验证测试?

我摆弄了repeat 函数,但无法让它从if else 正确返回。

【问题讨论】:

  • 你不能再打电话给exfun吗?
  • while 循环可能符合要求。这将一直返回到循环的开头,直到您说可以跳出它为止。

标签: r function loops repeat


【解决方案1】:

我并没有真正回答你的问题,但我会给你一个可能对你有帮助的例子(可能有人会给出改进的提示)。

您可以设置while 循环并设置条件以继续循环或结束循环,就像这样:

i <- 1
while (T) {
  print(i)
  i <- i + 1

  if (i==5) {
    print("NEXT")
    next
  }

  if (i==10) break
}

如您所见,if 和 next 条件在您的代码中执行某些操作,并在命令 print("NEXT") 之后继续运行它。此外,break 位于停止循环的条件内。

我希望它有所帮助,因为你的例子很难给出完整的答案。

【讨论】:

    猜你喜欢
    • 2017-03-16
    • 2020-04-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-08
    • 2015-07-19
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    相关资源
    最近更新 更多