R Language

Get user input

Syntax#

  • variable <- readline(prompt = “Any message for user”)

  • name <- readline(prompt = “What’s your name”)

User input in R

Sometimes it can be interesting to have a cross-talk between the user and the program, one example being the swirl package that had been designed to teach R in R.

One can ask for user input using the readline command:

name <- readline(prompt = "What is your name?")

The user can then give any answer, such as a number, a character, vectors, and scanning the result is here to make sure that the user has given a proper answer. For example:

result <- readline(prompt = "What is the result of 1+1?")
while(result!=2){
    readline(prompt = "Wrong answer. What is the result of 1+1?")
}

However, it is to be noted that this code be stuck in a never-ending loop, as user input is saved as a character.

We have to coerce it to a number, using as.numeric:

result <- as.numeric(readline(prompt = "What is the result of 1+1?"))
while(result!=2){
    readline(prompt = "Wrong answer. What is the result of 1+1?")
}

This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow