Learn R Online

R - How to take input from User

In this article you will learn to take input from user in R with readline() function as a text string or convert it in to an integer or a decimal value using as.integer() and as.numeric() functions.

While programming in R, very often we require to take input from user and convert it in to a desired format. To take input from user the most common function is readline(). This function reads the input entered by user and returns it as a text string. If you have to deal with text this value returned is ok. However, if you want to take a number from user then you will have to convert the input.

If you are an absolute beginner in R and want to learn R for data analysis or data science from R experts I will strongly suggest you to see this R for Absolute Beginners Course

Example: Take User input 

user <- readline(prompt="Enter your name: ")
print(paste(user, "welcome to R Programming")

user is the variable which will hold the value entered. readline() is the function which is used to take input from user. prompt is the line of text shown on console to guide what to input. print() function is used to print on console, and paste() function is used to concatenate two text strings.


> Enter your name: User
[1] User welcome to R Programming

Example: Take integer as input from user

name <- readline(prompt="Enter your name: ")
age <- readline(prompt="Enter your age:  ")
age <- as.integer(age)
print(paste(name, " you are ", age, "years old")

> Enter your name: User
> Enter your age: 21
[1] User you are 21 years old

In this example as.integer() function converts the text string entered into an integer which is later concatenated with name and printed on console.

Example: Take double or decimal as input

x <- readline(prompt= "Enter a floating point value: ")
x <- as.numeric(x)

> Enter a floating point value: 2.345
[1] 2.345
[1] double

In this example as.numeric() function is used to convert text string in to a numeric value or floating point value.