r语言 - 等待,直到用户输入一个值,并根据该值运行一组代码



我想做一个程序,其中用户将被要求输入位置,并根据该位置值,它应该运行一组特定的代码。它应该等待,直到用户输入位置的值。

readinteger <- function()
 { 
    n <- readline(prompt="Enter your location: ")
    n <- as.integer(n)
    if (is.na(n))
   return(as.integer(n))
  }
LC <- readinteger()
  if ( LC== 1)
{
 print(x)
}
 else if ( LC == 2)
 {
print(y)
} 
else 
print(z)

但是这里它直接进入if循环然后要求输入位置

如果您在readinteger函数中包含if语句来控制打印,这将工作得很好。这样,readline将按照预期的方式运行(等待用户输入),然后自动移动到打印命令。

readinteger <- function()
{ 
  n <- readline(prompt="Enter your location: ")
  n <- as.integer(n)
  x <- "You are at location one."
  y <- "You are at location two."
  z <- "You are lost."
  if ( n == 1)
    {
      print(x)
    }
  else if ( n == 2)
  {
    print(y)
  } 
  else 
    print(z)  
}
readinteger()

您的代码中有一个没有做任何事情的if (is.na(n)),但我的猜测是您想要包含一个检查以确保用户提供了有效的输入。如果是这样,您可能会发现while循环很有用,这样用户就可以在出现错误时纠正他们的输入。例如:

readinteger <- function()
{ 
  n <- NULL
  while( !is.integer(n) ){
    n <- readline(prompt="Enter your location: ")
    n <- try(suppressWarnings(as.integer(n)))
    if( is.na(n) ) {
      n <- NULL
      message("nYou must enter an integer. Please try again.")
    }
  }
  x <- "You are at location one."
  y <- "You are at location two."
  z <- "You are lost."
  if ( n == 1)
    {
      print(x)
    }
  else if ( n == 2)
  {
    print(y)
  } 
  else 
    print(z)  
}
readinteger()

好的。我认为这与一次性运行整个文件有关。如果你在rstudio中运行它,并且每次只运行一步,也就是以交互的方式运行,它就会起作用。

根据?readline的文档:'在非交互式使用中,结果就好像响应是RETURN,值是"。在这种情况下,一种解决方案是再次调用该函数,如下所示:http://www.rexamples.com/4/Reading%20user%20input

我不能百分之百肯定它能正常工作。

对于您的问题的更复杂的解决方案,您可以看到这个问题:

(注意:我添加这个作为答案只是为了格式化。这不是一个真正的答案)

相关内容

最新更新