【问题标题】:user input in R (Rscript and Widows command prompt)R 中的用户输入(Rscript 和 Widows 命令提示符)
【发布时间】:2023-12-26 04:20:01
【问题描述】:

我想知道,如何在 Windows 命令提示符下使用Rscript 运行 r 脚本并要求用户输入。

到目前为止,我已经找到了有关如何在 R 的交互式 shell 中请求用户输入的答案。对readline()scan() 进行相同操作的任何努力都失败了。

示例:

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

Uinput <- function() {
    message(prompt"Enter X1 value here: ")
    x <- readLines()
}

这是要走的路吗?任何额外的论点? as.numeric 有帮助吗?我如何返回X1?实施是否会因操作系统而异?

谢谢。

【问题讨论】:

    标签: r cmd user-input readline rscript


    【解决方案1】:

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

    你想要的是这样的:

    UIinput <- function(){
    
        #Ask for user input
        x <- readline(prompt = "Enter X1 value: ")
    
        #Return
        return(x)
    }
    

    您可能希望在那里进行一些错误处理(我可以提供 FALSE 或“芜菁”的 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)
    }
    

    【讨论】:

    • 唯一的问题是,即使代码似乎运行顺利且没有错误,终端中也没有任何反应。从字面上看没有..
    • 这……奇怪。我假设您实际上是在调用该函数?
    • @KapelNick 不要让我们悬而未决 - 你是如何解决的? :)。
    • cat("blablabla: ") x &lt;- readLines(con="stdin", 1) x &lt;- as.numeric(x) 为我工作
    • 那行得通,但我很困惑为什么上述解决方案没有。你是如何运行它的?
    最近更新 更多