Open In App

How to wait for a keypress in R ?

Last Updated : 17 Jun, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

R Programming language is robust and user-friendly, as it displays annotations and contexts for the desired input streams. We can pause the execution of a script and wait for the enter key to be pressed by the user into the console. This can be done using various standard methods in base R. 

Method 1 : Using readline() method

In order to prompt to print on the console after the Enter key is pressed, we can use the readline() method in base R. The readline() method in R language reads a line from the terminal. The output is returned as a character vector of length one. The leading, as well as the trailing spaces, are stripped from the returned output.

Syntax:

readline(prompt = “”)

prompt – the string displayed upon prompting the user for input. Mostly terminates with a ” ” (space) character.

Example:

R




# read line 
readline(prompt="Press [enter] to proceed")


Output

The invisible method in R is used to return a (temporarily) invisible copy of an object. It returns an arbitrary object which assigns the values but does not print it on the console when they are not assigned.

Syntax:

invisible (x)

Example:

R




# read line 
invisible(readline(prompt="Press [enter] to proceed"))


Output

Method 2 : Using scan() method

scan() method in base R is used to scan and read data into the working space. It read the input data into a vector or list or from file object establishing the file connection stream. This method fails when we enter any character string, that cannot be treated as a number. 

Example:

R




str <- "Press [enter] to proceed"
print (str)
  
# scan a new number
num <- scan(n=1)


Output



Like Article
Suggest improvement
Share your thoughts in the comments