(console) user interaction in R?
I am sure you all know the "hit return to show next plot" statement when executing the plot command on a regression object. I wonder how I can do this kind of interaction on my own in R. I found a couple of pos开发者_开发知识库ts on the mailing list, but nothing really comprehensive. Most of the it dealt with menu() and different OSes GUIs. I am just looking to create something like:
Please enter sample size n:
> 1000
#execution of
rnorm(1000)
Probably I have just missed some part of the documentation and simply can't find the right words to google...
Not readLines
but readline
.
n <- as.integer(readline(prompt = "Please enter sample size > "))
A slightly fancier implementation:
read_value <- function(prompt_text = "", prompt_suffix = getOption("prompt"), coerce_to = "character")
{
prompt <- paste(prompt_text, prompt_suffix)
as(readline(prompt), coerce_to)
}
read_value("Please enter sample size", coerce_to = "integer")
You can use readLines
, but I'm sure there are other ways too...
ask = function( prompt ) {
cat( paste( prompt, ':' ) )
readLines( n=1 )
}
n = as.integer( ask( 'Please enter sample size n' ) )
精彩评论