2017-08-29 77 views
2

我不能找到解决这个特定的问题,尽管或多或少类似的问题已经在之前的质疑:[R脚本

从bash运行脚本很容易,但是一旦需要用户交互,我找不到解决方案。请考虑例子:

userInput<-function(question) { 
    n = 0 
    while(n < 1){ 
    n <- readline(question) 
    n <- ifelse(grepl("\\D",n),-1,as.integer(n)) 
    if(is.na(n)){break} # breaks when hit enter 
    } 
    return(n) 
} 

investedLow<- userInput("Invested value in low risk since last time: ") 

现在,如果我这个脚本保存为test.R并运行它R --no-save < teste.R整个脚本的运行和用户输入的时间不会发生。例如,该脚本在Rstudio中运行良好。

  • 如何等待脚本中的用户输入在命令行中运行?

回答

0

这是一个总的黑客,再利用一个非常特殊的专用包为您的更普遍的问题:

library(getPass) 
userInput<-function(question) { 
    n = 0 
    while(n < 1){ 
     n <- getPass::getPass(msg = question) 
     n <- ifelse(grepl("\\D",n),-1,as.integer(n)) 
     if(is.na(n)){break} # breaks when hit enter 
    } 
    return(n) 
} 

investedLow <- userInput("Invested value in low risk since last time: ") 
print(investedLow) 

也许关于这个最糟糕的是,getPass隐藏用户输入。必须有一种方法来修改源代码来解决这个问题。

更新:提供了getpass author pointed out,由于使用readLines略有不同的解决方案可能是简单的:

cat(question) 
readLines(file("stdin"), n=1)