Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 669
Matt Bannert Avatar asked Apr 13 '11 09:04

Matt Bannert


People also ask

How do I prompt a user in R?

When we are working with R in an interactive session, we can use readline() function to take input from the user (terminal). This function will return a single element character vector.

How do I take user input from Matrix in R?

To enter the values in two rows we use nrow = 2 . To enter values in columns use ncol = “integer”. byrow =True tells R to enter the values row wise. We can also enter the elements using c() function.

Does R have user input?

Like other programming languages in R it's also possible to take input from the user.


2 Answers

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")
like image 151
Richie Cotton Avatar answered Sep 30 '22 08:09

Richie Cotton


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' ) )
like image 27
tim_yates Avatar answered Sep 30 '22 09:09

tim_yates