R 中的用户输入(Rscript 和 Widows 命令提示符)

5 cmd user-input r readline rscript

我想弄清楚,如何运行 r 脚本,Rscript在 Windows 命令提示符中使用并要求用户输入。

到目前为止,我已经找到了如何在 R 的交互式 shell 中请求用户输入的答案。readline()任何对或做同样事情的努力都 scan()失败了。

例子:

我有一个多项式y=cX,其中X可以取多个值X1X2X3等等。C变量是已知的,所以为了计算 的值,我需要y向用户询问这些Xi值并将它们存储在我的脚本中的某个位置。

Uinput <- function() {
    message(prompt"Enter X1 value here: ")
    x <- readLines()
}
Run Code Online (Sandbox Code Playgroud)

这是要走的路吗?还有其他论据吗?会as.numeric帮忙吗?我该如何返回X1?实施会因操作系统而异吗?

谢谢。

小智 4

这是一般的方法,但实现需要一些工作:你不需要 readLines,你需要 readline (是的,名称很相似。是的,这是愚蠢的。R 充满了愚蠢的东西;)。

你想要的是这样的:

UIinput <- function(){

    #Ask for user input
    x <- readline(prompt = "Enter X1 value: ")

    #Return
    return(x)
}
Run Code Online (Sandbox Code Playgroud)

不过,您可能想要在那里进行一些错误处理(我可以提供 FALSE 或“turnip”的 X1 值)和一些类型转换,因为 readline 返回单项字符向量:提供的任何数字输入可能应该是转换为数字输入。因此,一个很好的、用户验证的方法可能是......

UIinput <- function(){

    #Ask for user input
    x <- readline(prompt = "Enter X1 value: ")

    #Can it be converted?
    x <- as.numeric(x)

    #If it can't, be have a problem
    if(is.na(x)){

         stop("The X1 value provided is not valid. Please provide a number.")

    }

    #If it can be, return - you could turn the if into an if/else to make it more
    #readable, but it wouldn't make a difference in functionality since stop()
    #means that if the if-condition is met, return(x) will never actually be
    #evaluated.
    return(x)
}
Run Code Online (Sandbox Code Playgroud)

  • `cat("blablabla: ") x &lt;- readLines(con="stdin", 1) x &lt;- as.numeric(x)` 为我工作 (2认同)