等到用户输入一个值并根据该值运行一组代码

时间:2016-09-21 07:43:05

标签: r loops case

我想制作一个程序,要求用户输入该位置,并根据该位置值运行一组特定的代码。它应该等到用户输入位置值。

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 循环,然后要求输入位置

2 个答案:

答案 0 :(得分:0)

确定。我认为这与一次运行整个文件有关。 如果你在Rsudio中运行它并且一次运行一步,即交互式,它将起作用。

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

我不是100%肯定它没有故障。

对于问题的更复杂解决方案,您可以看到以下问题:Make readline wait for input in R

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

答案 1 :(得分:0)

如果您在if函数中包含readinteger语句来控制打印,这将正常工作。这样,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()
相关问题