Matt Bannert
Matt Bannert

Reputation: 28264

(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 posts 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...

Upvotes: 5

Views: 1785

Answers (2)

Richie Cotton
Richie Cotton

Reputation: 121057

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

Upvotes: 5

tim_yates
tim_yates

Reputation: 171074

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

Upvotes: 1

Related Questions