4

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

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

例子:

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

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

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

谢谢。

4

1 回答 1

3

That's the general way to go, but the implementation needs some work: you don't want readLines, you want readline (yes, the name is similar. Yes, this is dumb. R is filled with silly things ;).

What you want is something like:

UIinput <- function(){

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

    #Return
    return(x)
}

You probably want to do some error-handling there, though (I could provide an X1 value of FALSE, or "turnip"), and some type conversion, since readline returns a one-entry character vector: any numeric input provided should probably be converted to, well, a numeric input. So a nice, user-proof way of doing this might be...

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)
}
于 2014-04-06T19:51:41.993 回答