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.
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
Take User input
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  User welcome to
Take integer as input from user
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  User you are 21
In this example as.integer() function converts the text string entered
into an integer which is later concatenated with name and printed on
Take double or decimal as input
readline(prompt= "Enter a floating point value: ") x <-
as.numeric(x) print(x) print(typeof(x))
> Enter a
floating point value: 2.345  2.345  double
In this example as.numeric() function is used to convert text string in
to a numeric value or floating point value.