The Wayback Machine - https://web.archive.org/web/20241006150557/https://www.geeksforgeeks.org/data-structures-in-r-programming/
Open In App

Data Structures in R Programming

Last Updated : 26 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A data structure is a particular way of organizing data in a computer so that it can be used effectively. The idea is to reduce the space and time complexities of different tasks. Data structures in R programming are tools for holding multiple values. 

R’s base data structures are often organized by their dimensionality (1D, 2D, or nD) and whether they’re homogeneous (all elements must be of the identical type) or heterogeneous (the elements are often of various types). This gives rise to the six data types which are most frequently utilized in data analysis.

The most essential data structures used in R include: 

Vectors

A vector is an ordered collection of basic data types of a given length. The only key thing here is all the elements of a vector must be of the identical data type e.g homogeneous data structures. Vectors are one-dimensional data structures.

Example:  

R
# R program to illustrate Vector

# Vectors(ordered collection of same data type)
X = c(1, 3, 5, 7, 8)

# Printing those elements in console
print(X)

Output: 

[1] 1 3 5 7 8

Lists

A list is a generic object consisting of an ordered collection of objects. Lists are heterogeneous data structures. These are also one-dimensional data structures. A list can be a list of vectors, list of matrices, a list of characters and a list of functions and so on.

Example:  

R
# R program to illustrate a List

# The first attributes is a numeric vector
# containing the employee IDs which is 
# created using the 'c' command here
empId = c(1, 2, 3, 4)

# The second attribute is the employee name 
# which is created using this line of code here
# which is the character vector 
empName = c("Debi", "Sandeep", "Subham", "Shiba")

# The third attribute is the number of employees
# which is a single numeric variable.
numberOfEmp = 4

# We can combine all these three different
# data types into a list
# containing the details of employees
# which can be done using a list command
empList = list(empId, empName, numberOfEmp)

print(empList)

Output: 

[[1]]
[1] 1 2 3 4

[[2]]
[1] "Debi" "Sandeep" "Subham" "Shiba"

[[3]]
[1] 4

Dataframes

Dataframes are generic data objects of R which are used to store the tabular data. Dataframes are the foremost popular data objects in R programming because we are comfortable in seeing the data within the tabular form. They are two-dimensional, heterogeneous data structures. These are lists of vectors of equal lengths. 

Data frames have the following constraints placed upon them: 

  • A data-frame must have column names and every row should have a unique name.
  • Each column must have the identical number of items.
  • Each item in a single column must be of the same data type.
  • Different columns may have different data types.

To create a data frame we use the data.frame() function.

Example:  

R
# R program to illustrate dataframe

# A vector which is a character vector
Name = c("Amiya", "Raj", "Asish")

# A vector which is a character vector
Language = c("R", "Python", "Java")

# A vector which is a numeric vector
Age = c(22, 25, 45)

# To create dataframe use data.frame command
# and then pass each of the vectors 
# we have created as arguments
# to the function data.frame()
df = data.frame(Name, Language, Age)

print(df)

Output: 

   Name Language Age
1 Amiya R 22
2 Raj Python 25
3 Asish Java 45

Matrices

A matrix is a rectangular arrangement of numbers in rows and columns. In a matrix, as we know rows are the ones that run horizontally and columns are the ones that run vertically. Matrices are two-dimensional, homogeneous data structures.
Now, let’s see how to create a matrix in R. To create a matrix in R you need to use the function called matrix. The arguments to this matrix() are the set of elements in the vector. You have to pass how many numbers of rows and how many numbers of columns you want to have in your matrix and this is the important point you have to remember that by default, matrices are in column-wise order. 

Example:  

R
# R program to illustrate a matrix

A = matrix(
    # Taking sequence of elements
    c(1, 2, 3, 4, 5, 6, 7, 8, 9), 
    
    # No of rows and columns
    nrow = 3, ncol = 3,  

    # By default matrices are 
    # in column-wise order 
    # So this parameter decides
    # how to arrange the matrix          
    byrow = TRUE                             
)

print(A)

Output: 

     [,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9

Arrays

Arrays are the R data objects which store the data in more than two dimensions. Arrays are n-dimensional data structures. For example, if we create an array of dimensions (2, 3, 3) then it creates 3 rectangular matrices each with 2 rows and 3 columns. They are homogeneous data structures.

Now, let’s see how to create arrays in R. To create an array in R you need to use the function called array(). The arguments to this array() are the set of elements in vectors and you have to pass a vector containing the dimensions of the array. 

Example:  

Python3
# R program to illustrate an array

A = array(
    # Taking sequence of elements
    c(1, 2, 3, 4, 5, 6, 7, 8),

    # Creating two rectangular matrices 
    # each with two rows and two columns
    dim = c(2, 2, 2)                        
)

print(A)

Output: 

, , 1

[,1] [,2]
[1,] 1 3
[2,] 2 4

, , 2

[,1] [,2]
[1,] 5 7
[2,] 6 8

Factors

Factors are the data objects which are used to categorize the data and store it as levels. They are useful for storing categorical data. They can store both strings and integers. They are useful to categorize unique values in columns like “TRUE” or “FALSE”, or “MALE” or “FEMALE”, etc.. They are useful in data analysis for statistical modeling.

Now, let’s see how to create factors in R. To create a factor in R you need to use the function called factor(). The argument to this factor() is the vector. 

Example:  

R
# R program to illustrate factors

# Creating factor using factor()
fac = factor(c("Male", "Female", "Male",
               "Male", "Female", "Male", "Female"))

print(fac)

Output: 

[1] Male   Female Male   Male   Female Male   Female
Levels: Female Male

Tibbles

Tibbles are an enhanced version of data frames in R, part of the tidyverse. They offer improved printing, stricter column types, consistent subsetting behavior, and allow variables to be referred to as objects. Tibbles provide a modern, user-friendly approach to tabular data in R.

Now, let’s see how we can create a tibble in R. To create tibbles in R we can use the tibble function from the tibble package, which is part of the tidyverse.

Example:

R
# Load the tibble package
library(tibble)

# Create a tibble with three columns: name, age, and city
my_data <- tibble(
  name = c("Sandeep", "Amit", "Aman"),
  age = c(25, 30, 35),
  city = c("Pune", "Jaipur", "Delhi")
)

# Print the tibble
print(my_data)

Output:

  name        age    city
<chr> <dbl> <chr>
1 Sandeep 25 Pune
2 Amit 30 Jaipur
3 Aman 35 Delhi


 



Previous Article
Next Article

Similar Reads

Data Wrangling in R Programming - Data Transformation
A dataset can be presented in many different ways to the world. Let us look at one of the most essential and fundamental distinctions, whether a dataset is wide or long. The difference between wide and long datasets condenses to whether we prefer to have more rows in our dataset or more columns. A dataset that spotlights on putting additional data
3 min read
Convert an Object to Data Frame in R Programming - as.data.frame() Function
as.data.frame() function in R Programming Language is used to convert an object to data frame. These objects can be Vectors, Lists, Matrices, and Factors. Syntax: as.data.frame(object) Parameters: object: Vector, Matrix, factor, or data frameR - as.data.frame() Function ExampleExample 1: Basic example of as.data.frame() Function in R C/C++ Code # R
2 min read
Check if the Object is a Data Frame in R Programming - is.data.frame() Function
is.data.frame() function in R Language is used to return TRUE if the specified data type is a data frame else return FALSE. R data.frame is a powerful data type, especially when processing table (.csv). It can store the data as row and columns according to the table. Syntax: is.data.frame(x) Parameters: x: specified data.frame Example 1: # R progra
1 min read
Convert a Data Frame into a Numeric Matrix in R Programming - data.matrix() Function
data.matrix() function in R Language is used to create a matrix by converting all the values of a Data Frame into numeric mode and then binding them as a matrix. Syntax: data.matrix(df) Parameters: df: Data frame to be converted. Example 1: # R program to convert a data frame # into a numeric matrix # Creating a dataframe df1 = data.frame( "Na
2 min read
Modify Data of a Data Frame with an Expression in R Programming - with() Function
with() function in R Language is used to modify data of a data frame by evaluating an expression within the arguments of the function. Syntax: with(x, expr) Parameters: x: Data frame expr: Expression to modify data Example 1: # R program to modify data of an object # Calling predefined data set BOD # Calling with() function with(BOD, {BOD$demand
1 min read
Generate a set of Sample data from a Data set in R Programming - sample() Function
sample() function in R Language creates random sample based on the parameters provided in the function call. It takes either a vector or a positive integer as the object in the function parameter. Syntax: sample(x, size, replace) Parameters: x: indicates either vector or a positive integer or data frame size: indicates size of sample to be taken re
2 min read
data.table vs data.frame in R Programming
data.table in R is an enhanced version of the data.frame. Due to its speed of execution and the less code to type it became popular in R. The purpose of data.table is to create tabular data same as a data frame but the syntax varies. In the below example let we can see the syntax for the data table: C/C++ Code DataTable = data.table(name = c("
3 min read
Is it Mandatory to Learn R Programming Language for Becoming a Master in Data Science and Big Data?
It is not mandatory to learn R programming to become a master in data science and big data, but it is highly beneficial. R is one of the leading languages for statistical analysis and has powerful tools for data visualization, which are crucial skills in data science. However, proficiency in other languages like Python can also provide a comprehens
3 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
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
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
Reading Tabular Data from files in R Programming
Often, the data which is to be read and worked upon is already stored in a file but is present outside the R environment. Hence, importing data into R is a mandatory task in such circumstances. The formats which are supported by R are CSV, JSON, Excel, Text, XML, etc. The majority of times, the data to be read into R is in tabular format. The funct
4 min read
Comparing values of data frames in R Programming - all_equal() Function
all_equal() function in R Language is used to compare the values between dataframes. Syntax: all_equal(target, current, check.attributes, check.names) Parameters: target: object to comparecurrent: object to be compared withcheck.attributes: If attributes of both be comparedcheck.names: If names be comparedR - compare values of data frames Example 1
2 min read
Convert type of data object in R Programming - type.convert() Function
type.convert() function in R Language is used to compute the data type of a particular data object. It can convert data object to logical, integer, numeric, or factor. Syntax: type.convert(x) Parameter: x: It can be a vector matrix or an array Example 1: Apply type.convert to vector of numbers # R program to illustrate # type.convert to vector of n
2 min read
Create Matrix and Data Frame from Lists in R Programming
In R programming, there 5 basic objects. Lists are the objects that can contain heterogeneous types of elements, unlike vectors. Matrices can contain the same type of elements or homogeneous elements. On the other hand, data frames are similar to matrices but have an advantage over matrices to keep heterogeneous elements. In this article, we'll lea
3 min read
Check if Object is of the Character Data type in R Programming - is.character() Function
is.character() Function in R Language is used to check if the object is of the form of a string/character or not. It will return true if any element of the object is of the character data type. Syntax: is.character(Object) Parameter: Object: It could be an array, list, vector, etc. Example 1: # R Program to illustrate # the use of is.character func
1 min read
Get Transpose of a Matrix or Data Frame in R Programming - t() Function
t() function in R Language is used to calculate transpose of a matrix or Data Frame. Syntax: t(x) Parameters: x: matrix or data frame Example 1: # R program to illustrate # t function # Getting R Biochemical Oxygen Demand Dataset BOD # Calling t() function t(BOD) Output: Time demand 1 1 8.3 2 2 10.3 3 3 19.0 4 4 16.0 5 5 15.6 6 7 19.8 [, 1] [, 2] [
1 min read
Compute the Hyperbolic arctangent of numeric data in R Programming - atanh() Function
atanh() function in R Language is used to compute the hyperbolic arctangent of numeric data. Syntax: atanh(x) Parameters: x: Numeric value, array or vector. Example 1: # R program to illustrate # atanh function # Calling atanh() function over # different numbers atanh(0) atanh(1) atanh(0.9) atanh(-0.8) Output: [1] 0 [1] Inf [1] 1.472219 [1] -1.0986
1 min read
Compute the Hyperbolic arcsine of numeric data in R Programming – asinh() Function
asinh() function in R Language is used to compute the hyperbolic arcsine of numeric data. Syntax:asinh(x) Parameters: x: Numeric value, array or vector Example 1: # R program to illustrate # asinh function # Calling asinh() function over # different numbers asinh(0) asinh(1) Output: [1] 0 [1] 0.8813736 Example 2: # R program to illustrate # asinh f
1 min read
Compute the Hyperbolic arccosine of numeric data in R Programming – acosh() Function
acosh() function in R Language is used to compute the hyperbolic arccosine of numeric data. Syntax:acosh(x) Parameters: x: Numeric value, array or vector Example 1: # R program to illustrate # acosh function # Calling acosh() function over # different numbers acosh(0) acosh(1) Output: [1] NaN [1] 0 Example 2: # R program to illustrate # acosh funct
1 min read
Getting class of different data types in R Programming - class() Function
class() function in R Language is used to return the class of data used as the arguments. Syntax: class(x) Parameters: x: specified data Example 1: # R program to illustrate # class function # Specifying "Biochemical oxygen demand" # data set x <- BOD x # Calling class() function class(x) Output: Time demand 1 1 8.3 2 2 10.3 3 3 19.0 4
1 min read
Getting type of different data types in R Programming - typeof() Function
typeof() function in R Language is used to return the types of data used as the arguments. Syntax: typeof(x) Parameters: x: specified data Example 1: # R program to illustrate # typeof function # Specifying "Biochemical oxygen demand" # data set x <- BOD x # Calling typeof() function typeof(x) Output: Time demand 1 1 8.3 2 2 10.3 3 3 1
1 min read
Merge Two Data Frames by common Columns in R Programming - merge() Function
merge() function in R Language is used to merge two data frames by common columns. Syntax: merge(arg1, arg2, by.x, by.y) Parameters: arg1 and arg2: Data frames to be merged by.x: Common argument of first data frame by.y: Common argument of second data frame Example 1: # R program to merge two data frames # Creating data frames df1 <- data.frame(
1 min read
Creating a Data Frame from Vectors in R Programming
A vector can be defined as the sequence of data with the same datatype. In R, a vector can be created using c() function. R vectors are used to hold multiple data values of the same datatype and are similar to arrays in C language. Data frame is a 2 dimensional table structure which is used to hold the values. In the data frame, each column contain
5 min read
Reordering of a Data Set in R Programming - arrange() Function
arrange() function in R Language is used for reordering of table rows with the help of column names as expression passed to the function. Syntax: arrange(x, expr) Parameters: x: data set to be reordered expr: logical expression with column name Example 1: # R program to reorder a data set # Loading library library(dplyr) # Calling dataset x <- B
1 min read
Check if an Object is of Complex Data Type in R Programming - is.complex() Function
is.complex() function in R Language is used to check if the object passed to it as argument is of complex data type. Syntax: is.complex(x) Parameters: x: Object to be checked Example 1: # R program to check if # object is of complex type # Calling is.complex() function is.complex(1 + 0i) is.complex(1.5 + 2i) is.complex(-1.5 + 2i) Output: [1] TRUE [
1 min read
Convert a Data Frame into a Molten Form in R Programming - melt() Function
function in R Language is used to combine multiple columns of s Data Frame into a single column. Syntax: melt(x, na.rm, value.name) Parameters: x: data to be melted na.rm: Boolean value to remove NA value.name: Setting column names Example 1: # R program to reshape data frame # Loading library library(reshape) # Creating a data frame a <- data.f
2 min read
Choose Specific Columns of a Data Frame in R Programming - select() Function
select() function in R Language is used to choose whether a column of the data frame is selected or not. Syntax: select(x, expr) Parameters: x: Data frame expr: condition for selection Example 1: # R program to select specific columns # Loading library library(dplyr) # Create a data frame d <- data.frame( name = c("Abhi", "Bhavesh
2 min read
Condense Column Values of a Data Frame in R Programming - summarise() Function
summarise() function in R Language is used to condense various values of column of a data frame to one value. Syntax: summarise(x, expr) Parameters: x: Data Frame expr: Operation to condense data Example 1: # R program to condense data # of a data frame # Loading library library(dplyr) # Create a data frame d <- data.frame( name = c("Abhi
1 min read
Take Random Samples from a Data Frame in R Programming - sample_n() Function
sample_n() function in R Language is used to take random sample specimens from a data frame. Syntax: sample_n(x, n) Parameters: x: Data Frame n: size/number of items to select Example 1: # R program to collect sample data # from a data frame # Loading library library(dplyr) # Create a data frame d <- data.frame( name = c("Abhi", "
1 min read