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