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...
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.
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.
Like other programming languages in R it's also possible to take input from the user.
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' ) )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With