user input in R (Rscript and Widows command prompt)

[亡魂溺海] 提交于 2020-01-12 04:00:08

问题


I am trying to figure out, how can i run an r script, using Rscript in windows command prompt and ask for user input.

So far, i have found answers on how do ask for user input in R's interactive shell. Any effort in doing the same with readline() or scan() has failed.

example:

I have a polynomial y=cX where X can take more than one values X1,X2,X3 and so on. C variable is know, so what i need in order to calculate the value of y is to ask the user for the Xi values and store them somewhere inside my script.

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

Is this the way to go? Any additional arguments? Will as.numeric help? How do i return X1? And will the implementation differ depending on the OS?

Thanks.


回答1:


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)
}


来源:https://stackoverflow.com/questions/22895370/user-input-in-r-rscript-and-widows-command-prompt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!