The Wayback Machine - https://web.archive.org/web/20240828110802/https://www.geeksforgeeks.org/taking-input-from-user-in-r-programming/
Open In App

Taking Input from User in R Programming

Last Updated : 07 Jul, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Developers often have a need to interact with users, either to get data or to provide some sort of result. Most programs today use a dialog box as a way of asking the user to provide some type of input. Like other programming languages in R it’s also possible to take input from the user. For doing so, there are two methods in R. 
 

  • Using readline() method
  • Using scan() method

 

Using readline() method

In R language readline() method takes input in string format. If one inputs an integer then it is inputted as a string, lets say, one wants to input 255, then it will input as “255”, like a string. So one needs to convert that inputted value to the format that he needs. In this case, string “255” is converted to integer 255. To convert the inputted value to the desired data type, there are some functions in R, 
 

  • as.integer(n); —> convert to integer
  • as.numeric(n); —> convert to numeric type (float, double etc)
  • as.complex(n); —> convert to complex number (i.e 3+2i)
  • as.Date(n) —> convert to date …, etc

 

Syntax: 
var = readline(); 
var = as.integer(var);
Note that one can use “<-“ instead of “=” 
 

Example: 
 

R




# R program to illustrate
# taking input from the user
 
# taking input using readline()
# this command will prompt you
# to input a desired value
var = readline();
 
# convert the inputted value to integer
var = as.integer(var);
 
# print the value
print(var)


Output: 
 

255
[1] 255

 

One can also show message in the console window to tell the user, what to input in the program. To do this one must use a argument named prompt inside the readline() function. Actually prompt argument facilitates other functions to constructing of files documenting. But prompt is not mandatory to use all the time.
 

Syntax: 
var1 = readline(prompt = “Enter any number : “); 
or, 
var1 = readline(“Enter any number : “);

Example: 
 

R




# R program to illustrate
# taking input from the user
 
# taking input with showing the message
var = readline(prompt = "Enter any number : ");
 
# convert the inputted value to an integer
var = as.integer(var);
 
# print the value
print(var)


Output: 
 

Enter any number : 255
[1] 255

 

Taking multiple inputs in R

Taking multiple inputs in R language is same as taking single input, just need to define multiple readline() for inputs. One can use braces for define multiple readline() inside it.
 

Syntax: 
var1 = readline(“Enter 1st number : “); 
var2 = readline(“Enter 2nd number : “); 
var3 = readline(“Enter 3rd number : “); 
var4 = readline(“Enter 4th number : “);
or,
{ 
var1 = readline(“Enter 1st number : “); 
var2 = readline(“Enter 2nd number : “); 
var3 = readline(“Enter 3rd number : “); 
var4 = readline(“Enter 4th number : “); 
}

Example: 
 

R




# R program to illustrate
# taking input from the user
 
# taking multiple inputs
# using braces
{
    var1 = readline("Enter 1st number : ");
    var2 = readline("Enter 2nd number : ");
    var3 = readline("Enter 3rd number : ");
    var4 = readline("Enter 4th number : ");
}
 
# converting each value
var1 = as.integer(var1);
var2 = as.integer(var2);
var3 = as.integer(var3);
var4 = as.integer(var4);
 
# print the sum of the 4 number
print(var1 + var2 + var3 + var4)


Output: 
 

Enter 1st number : 12
Enter 2nd number : 13
Enter 3rd number : 14
Enter 4th number : 15
[1] 54

 

Taking String and Character input in R

 

To take string input is the same as an integer. For “String” one doesn’t need to convert the inputted data into a string because R takes input as string always. And for “character”, it needs to be converted to ‘character’. Sometimes it may not cause any error. One can take character input as same as string also, but that inputted data is of type string for the entire program. So the best way to use that inputted data as ‘character’ is to convert the data to a character.

 

Syntax:
string: 
var1 = readline(prompt = “Enter your name : “);
character: 
var1 = readline(prompt = “Enter any character : “); 
var1 = as.character(var1)

Example: 
 

R




# R program to illustrate
# taking input from the user
 
# string input
var1 = readline(prompt = "Enter your name : ");
 
# character input
var2 = readline(prompt = "Enter any character : ");
# convert to character
var2 = as.character(var2)
 
# printing values
print(var1)
print(var2)


Output: 
 

Enter your name : GeeksforGeeks
Enter any character : G
[1] "GeeksforGeeks"
[1] "G"

 

Using scan() method

Another way to take user input in R language is using a method, called scan() method. This method takes input from the console. This method is a very handy method while inputs are needed to taken quickly for any mathematical calculation or for any dataset. This method reads data in the form of a vector or list. This method also uses to reads input from a file also. 
 

Syntax: 
x = scan()
scan() method is taking input continuously, to terminate the input process, need to press Enter key 2 times on the console.

Example: 
This is simple method to take input using scan() method, where some integer number is taking as input and print those values in the next line on the console. 
 

R




# R program to illustrate
# taking input from the user
 
# taking input using scan()
x = scan()
# print the inputted values
print(x)


Output: 
 

1: 1 2 3 4 5 6
7: 7 8 9 4 5 6
13: 
Read 12 items
 [1] 1 2 3 4 5 6 7 8 9 4 5 6

Explanation: 
Total 12 integers are taking as input in 2 lines when the control goes to 3rd line then by pressing Enter key 2 times the input process will be terminated.
 

Taking double, string, character type values using scan() method

To take double, string, character types inputs, specify the type of the inputted value in the scan() method. To do this there is an argument called what, by which one can specify the data type of the inputted value.
 

Syntax: 
x = scan(what = double()) —-for double 
x = scan(what = ” “) —-for string 
x = scan(what = character()) —-for character 

Example: 
 

R




# R program to illustrate
# taking input from the user
 
# double input using scan()
d = scan(what = double())
 
# string input using 'scan()'
s = scan(what = " ")
 
# character input using 'scan()'
c = scan(what = character())
 
# print the inputted values
print(d) # double
print(s) # string
print(c) # character


Output: 
 

1: 123.321 523.458 632.147
4: 741.25 855.36
6: 
Read 5 items
1: geeksfor geeks gfg
4: c++ R java python
8: 
Read 7 items
1: g e e k s f o
8: r g e e k s
14: 
Read 13 items
[1] 123.321 523.458 632.147 741.250 855.360
[1] "geeksfor" "geeks"    "gfg"      "c++"      "R"        "java"     "python"  
[1] "g" "e" "e" "k" "s" "f" "o" "r" "g" "e" "e" "k" "s"

Explanation: 
Here, count of double items is 5, count of sorting items is 7, count of character items is 13.
 

Read File data using scan() method

To read file using scan() method is same as normal console input, only thing is that, one needs to pass the file name and data type to the scan() method.
 

Syntax: 
x = scan(“fileDouble.txt”, what = double()) —-for double 
x = scan(“fileString.txt”, what = ” “) —-for string 
x = scan(“fileChar.txt”, what = character()) —-for character

Example: 
 

R




# R program to illustrate
# taking input from the user
 
# string file input using scan()
s = scan("fileString.txt", what = " ")
 
# double file input using scan()
d = scan("fileDouble.txt", what = double())
 
# character file input using scan()
c = scan("fileChar.txt", what = character())
 
# print the inputted values
print(s) # string
print(d) # double
print(c) # character


Output: 
 

Read 7 items
Read 5 items
Read 13 items
[1] "geek"   "for"    "geeks"  "gfg"    "c++"    "java"   "python"
[1] 123.321 523.458 632.147 741.250 855.360
[1] "g" "e" "e" "k" "s" "f" "o" "r" "g" "e" "e" "k" "s"

Save the data file in the same location where the program is saved for better access. Otherwise total path of the file need to defined inside the scan() method.
 



Previous Article
Next Article

Similar Reads

Why is R programming taking over SPSS? What is the difference between the two?
Answer: R programming is gradually taking over SPSS because it is an open-source, flexible, and powerful tool that offers greater capabilities for statistical analysis, data visualization, and data manipulation. Unlike SPSS, which is commercial software with licensing fees, R is free to use and supported by a vast community that continually develop
3 min read
Applying User-defined Functions on Factor Levels of Dataset in R Programming - by() Function
by() function in R programming is an object-oriented wrapper function which performs the provided function on factor levels of the data set passed in the arguments of function call. Syntax: by(data, INDICES, FUN) Parameters: data: represents the dataset INDICES: represents the factor list of dataset FUN: represents the function to be performed on f
1 min read
What is the Relation Between R Programming and Hadoop Programming?
The relation between R programming and Hadoop revolves around integrating R with the Hadoop ecosystem to analyze large datasets that are stored in a Hadoop environment. R, primarily used for statistical analysis and data visualization, is not inherently built for handling big data. However, when combined with Hadoop, it can leverage Hadoop's distri
3 min read
How to plot user-defined functions in R?
Plotting user-defined functions in R is a common task for visualizing mathematical functions, statistical models, or custom data transformations. This article provides a comprehensive guide on how to plot user-defined functions in R, including creating simple plots, enhancing them with additional features, and customizing their appearance. Overview
3 min read
How to Validate Input to a Function Error in R
In this article, we will examine various methods for how to validate input to the function by using R Programming Language. How to validate input to the function?Validating input to a function in R is crucial for ensuring that your code behaves as expected and can handle various types of input gracefully. R language offers various methods to valida
5 min read
Getting the Modulus of the Determinant of a Matrix in R Programming - determinant() Function
determinant() function in R Language is a generic function that returns separately the modulus of the determinant, optionally on the logarithm scale, and the sign of the determinant. Syntax: determinant(x, logarithm = TRUE, ...) Parameters: x: matrix logarithm: if TRUE (default) return the logarithm of the modulus of the determinant Example 1: # R
2 min read
tidyr Package in R Programming
Packages in the R language are a collection of R functions, compiled code, and sample data. They are stored under a directory called “library” in the R environment. By default, R installs a set of packages during installation. One of the most important packages in R is the tidyr package. The sole purpose of the tidyr package is to simplify the proc
14 min read
Get Exclusive Elements between Two Objects in R Programming - setdiff() Function
setdiff() function in R Programming Language is used to find the elements which are in the first Object but not in the second Object. Syntax: setdiff(x, y) Parameters: x and y: Objects with sequence of itemsR - setdiff() Function ExampleExample 1: Apply setdiff to Numeric Vectors in R Language C/C++ Code # R program to illustrate # the use of setdi
2 min read
Add Leading Zeros to the Elements of a Vector in R Programming - Using paste0() and sprintf() Function
paste0() and sprintf() functions in R Language can also be used to add leading zeros to each element of a vector passed to it as argument. Syntax: paste0("0", vec) or sprintf("%0d", vec)Parameters: paste0: It will add zeros to vector sprintf: To format a vector(adding zeros) vec: Original vector dataReturns: Vectors by addition of leading zeros Exa
1 min read
Clustering in R Programming
Clustering in R Programming Language is an unsupervised learning technique in which the data set is partitioned into several groups called clusters based on their similarity. Several clusters of data are produced after the segmentation of data. All the objects in a cluster share common characteristics. During data mining and analysis, clustering is
6 min read
Compute Variance and Standard Deviation of a value in R Programming - var() and sd() Function
var() function in R Language computes the sample variance of a vector. It is the measure of how much value is away from the mean value. Syntax: var(x) Parameters: x : numeric vector Example 1: Computing variance of a vector # R program to illustrate # variance of vector # Create example vector x &lt;- c(1, 2, 3, 4, 5, 6, 7) # Apply var function in
1 min read
Compute Density of the Distribution Function in R Programming - dunif() Function
dunif() function in R Language is used to provide the density of the distribution function. Syntax: dunif(x, min = 0, max = 1, log = FALSE) Parameters: x: represents vector min, max: represents lower and upper limits of the distribution log: represents logical value for probabilities Example 1: # Create vector of random deviation u &lt;- runif(20)
1 min read
Compute Randomly Drawn F Density in R Programming - rf() Function
rf() function in R Language is used to compute random density for F Distribution. Syntax: rf(N, df1, df2) Parameters: N: Sample Size df: Degree of Freedom Example 1: # R Program to compute random values # of F Density # Setting seed for # random number generation set.seed(1000) # Set sample size N &lt;- 20 # Calling rf() Function y &lt;- rf(N, df1
1 min read
Data Handling in R Programming
R Programming Language is used for statistics and data analytics purposes. Importing and exporting of data is often used in all these applications of R programming. R language has the ability to read different types of files such as comma-separated values (CSV) files, text files, excel sheets and files, SPSS files, SAS files, etc. R allows its user
5 min read
Return a Matrix with Lower Triangle as TRUE values in R Programming - lower.tri() Function
lower.tri() function in R Language is used to return a matrix of logical values with lower triangle as TRUE. Syntax: lower.tri(x, diag) Parameters: x: Matrix object diag: Boolean value to include diagonal Example 1: # R program to print the # lower triangle of a matrix # Creating a matrix mat &lt;- matrix(c(1:9), 3, 3, byrow = T) # Calling lower.tr
1 min read
Print the Value of an Object in R Programming - identity() Function
identity() function in R Language is used to print the value of the object which is passed to it as argument. Syntax: identity(x) Parameters: x: An Object Example 1: # R program to print # the value of an object # Creating a vector x &lt;- c(1, 2, 3, 4) # Creating a list list1 &lt;- list(letters[1:6]) # Calling the identity function identity(x) ide
1 min read
Check if Two Objects are Equal in R Programming - setequal() Function
setequal() function in R Language is used to check if two objects are equal. This function takes two objects like Vectors, dataframes, etc. as arguments and results in TRUE or FALSE, if the Objects are equal or not. Syntax: setequal(x, y) Parameters: x and y: Objects with sequence of items Example 1: # R program to illustrate # the use of setequal(
1 min read
Random Forest with Parallel Computing in R Programming
Random Forest in R Programming is basically a bagging technique. From the name we can clearly interpret that this algorithm basically creates the forest with a lot of trees. It is a supervised classification algorithm. In a general scenario, if we have a greater number of trees in a forest it gives the best aesthetic appeal to all and is counted as
4 min read
R - Object Oriented Programming
In this article, we will discuss Object-Oriented Programming (OOPs) in R Programming Language. We will discuss the S3 and S4 classes, the inheritance in these classes, and the methods provided by these classes. OOPs in R Programming Language:In R programming, OOPs in R provide classes and objects as its key tools to reduce and manage the complexity
7 min read
Check for Presence of Common Elements between Objects in R Programming - is.element() Function
is.element() function in R Language is used to check if elements of first Objects are present in second Object or not. It returns TRUE for each equal value. Syntax: is.element(x, y) Parameters: x and y: Objects with sequence of items Example 1: # R program to illustrate # the use of is.element() function # Vector 1 x1 &lt;- c(1, 2, 3) # Vector 2 x2
1 min read
AB Testing With R Programming
Split testing is another name of A/B testing and it's a common or general methodology. It's used online when one wants to test a new feature or a product. The main agenda over here is to design an experiment that gives repeatable results and robust to make an informed decision to launch it or not. Generally, this test includes a comparison of two w
7 min read
Check if Elements of a Vector are non-empty Strings in R Programming - nzchar() Function
nzchar() function in R Language is used to test whether elements of a character vector are non-empty strings. Syntax: nzchar(x) Parameters: x: character vector Example 1: # R program to illustrate # nzchar function # Initializing a character vector x &lt;- c(&quot;GFG&quot;, &quot;gfg&quot;) y &lt;- c(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;) #
1 min read
Finding the length of string in R programming - nchar() method
nchar() method in R Programming Language is used to get the length of a character in a string object. Syntax: nchar(string) Where: String is object. Return: Returns the length of a string. R - length of string using nchar() ExampleExample 1: Find the length of the string in R In this example, we are going to see how to get the length of a string ob
2 min read
Data Reshaping in R Programming
Generally, in R Programming Language, data processing is done by taking data as input from a data frame where the data is organized into rows and columns. Data frames are mostly used since extracting data is much simpler and hence easier. But sometimes we need to reshape the format of the data frame from the one we receive. Hence, in R, we can spli
5 min read
Plotting Graphs using Two Dimensional List in R Programming
List is a type of an object in R programming. Lists can contain heterogeneous elements like strings, numeric, matrices, or even lists. A list is a generic vector containing other objects. Two-dimensional list can be created in R programming by creating more lists in a list or simply, we can say nested lists. The list() function in R programming is
2 min read
Make Elements of a Vector Unique in R Programming - make.unique() Function
make.unique() function in R Language is used to return elements of a vector with unique names by appending sequence numbers to duplicates. Syntax: make.unique(names, sep)Parameters: names: Character vector with duplicate names sep: Separator to be used Example 1: C/C++ Code # R program to make unique vectors # Calling make.unique() Function make.un
1 min read
Get or Set Levels of a Factor in R Programming - levels() Function
levels() function in R Language is used to get or set the levels of a factor. Syntax: levels(x) Parameters: x: Factor Object Example 1: # R program to get levels of a factor # Creating a factor gender &lt;- factor(c(&quot;female&quot;, &quot;male&quot;, &quot;male&quot;, &quot;female&quot;)); gender # Calling levels() function # to get the levels l
1 min read
Compute the gamma value of a Non-negative Numeric Vector in R Programming - gamma() Function
gamma() function in R Language is used to compute the gamma value of a numeric vector using the gamma function. Gamma function is basically, gamma(x) = factorial(x - 1) Syntax: gamma(x) Parameters: x: Non-negative Numeric Vector Example 1: # R program to calculate the gamma value # Calling gamma Function gamma(2) gamma(3) gamma(5) Output: [1] 1 [1]
1 min read
Compute Choleski factorization of a Matrix in R Programming - chol() Function
chol() function in R Language is used to compute the Choleski factorization of a real symmetric positive-definite square matrix. Syntax: chol(x, ...)Parameters: x: an object for which a method exists. The default method applies to real symmetric, positive-definite matrices Example 1: C/C++ Code # R program to illustrate # chol function # Initializi
2 min read
Classes in R Programming
Classes and Objects are basic concepts of Object-Oriented Programming that revolve around the real-life entities. Everything in R is an object. An object is simply a data structure that has some methods and attributes. A class is just a blueprint or a sketch of these objects. It represents the set of properties or methods that are common to all obj
4 min read
Article Tags :