The Wayback Machine - https://web.archive.org/web/20240927022928/https://www.geeksforgeeks.org/dataframe-operations-in-r/
Open In App

DataFrame Operations in R

Last Updated : 01 Apr, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

DataFrames are generic data objects of R which are used to store the tabular data. Data frames are considered to be the most popular data objects in R programming because it is more comfortable to analyze the data in the tabular form. Data frames can also be taught as mattresses where each column of a matrix can be of the different data types. DataFrame are made up of three principal components, the data, rows, and columns. 

Operations that can be performed on a DataFrame are: 
 

  • Creating a DataFrame
  • Accessing rows and columns
  • Selecting the subset of the data frame
  • Editing dataframes
  • Adding extra rows and columns to the data frame
  • Add new variables to dataframe based on existing ones
  • Delete rows and columns in a data frame

Creating a DataFrame

In the real world, a DataFrame will be created by loading the datasets from existing storage, storage can be SQL Database, CSV file, and an Excel file. DataFrame can also be created from the vectors in R. Following are some of the various ways that can be used to create a DataFrame:

Creating a data frame using Vectors: To create a data frame we use the data.frame() function in R. To create a data frame use data.frame() command and then pass each of the vectors you have created as arguments to the function. 

Example:  

Python3




# 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

Creating a data frame using data from a file: Dataframes can also be created by importing the data from a file. For this, you have to use the function called ‘read.table()‘.

Syntax:  

newDF = read.table(path="Path of the file")

To create a dataframe from a CSV file in R: 

Syntax:  

newDF = read.csv("FileName.csv")

Accessing rows and columns

The syntax for accessing rows and columns is given below,  

df[val1, val2]

df = dataframe object
val1 = rows of a data frame
val2 = columns of a data frame

So, this ‘val1‘ and ‘val2‘ can be an array of values such as “1:2” or “2:3” etc. If you specify only df[val2] this refers to the set of columns only, that you need to access from the data frame.

Example: Row selection  

Python3




# R program to illustrate operations
# on a data frame
 
# Creating a dataframe
df = data.frame(
  "Name" = c("Amiya", "Raj", "Asish"),
  "Language" = c("R", "Python", "Java"),
  "Age" = c(22, 25, 45)
)
print(df)
 
# Accessing first and second row
cat("Accessing first and second row\n")
print(df[1:2, ])


Output: 

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

Accessing first and second row
   Name Language Age
1 Amiya        R  22
2   Raj   Python  25

Example: Column selection 

Python3




# R program to illustrate operations
# on a data frame
 
# Creating a dataframe
df = data.frame(
  "Name" = c("Amiya", "Raj", "Asish"),
  "Language" = c("R", "Python", "Java"),
  "Age" = c(22, 25, 45)
)
print(df)
 
# Accessing first and second column
cat("Accessing first and second column\n")
print(df[, 1:2])


Output: 

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

Accessing first and second column
   Name Language
1 Amiya        R
2   Raj   Python
3 Asish     Java

Selecting the subset of the DataFrame

A subset of a DataFrame can also be created based on certain conditions with the help of following syntax.  

newDF = subset(df, conditions)
df = Original dataframe 
conditions = Certain conditions 
 

Example:  

Python3




# R program to illustrate operations
# on a data frame
 
# Creating a dataframe
df = data.frame(
  "Name" = c("Amiya", "Raj", "Asish"),
  "Language" = c("R", "Python", "Java"),
  "Age" = c(22, 25, 45)
)
print(df)
 
# Selecting the subset of the data frame
# where Name is equal to Amiya
# OR age is greater than 30
newDf = subset(df, Name =="Amiya"|Age>30)
 
cat("After Selecting the subset of the data frame\n")
print(newDf)


Output: 

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

After Selecting the subset of the data frame
   Name Language Age
1 Amiya        R  22
3 Asish     Java  45

Editing DataFrames

In R, DataFrames can be edited in two ways:
Editing data frames by direct assignments: Much like the list in R you can edit the data frames by a direct assignment. 

Example:  

Python3




# R program to illustrate operation on a data frame
 
# Creating a dataframe
df = data.frame(
  "Name" = c("Amiya", "Raj", "Asish"),
  "Language" = c("R", "Python", "Java"),
  "Age" = c(22, 25, 45)
)
cat("Before editing the dataframe\n")
print(df)
 
# Editing dataframes by direct assignments
# [[3]] accessing the top level components
# Here Age in this case
# [[3]][3] accessing inner level components
# Here Age of Asish in this case
df[[3]][3] = 30
 
cat("After edited the dataframe\n")
print(df)


Output: 

Before editing the data frame
   Name Language Age
1 Amiya        R  22
2   Raj   Python  25
3 Asish     Java  45

After edited the data frame
   Name Language Age
1 Amiya        R  22
2   Raj   Python  25
3 Asish     Java  30

Editing dataframes using the edit() command: 
Follow the given steps to edit a DataFrame:

Step 1: So, what you need to do for this is you have to create an instance of data frame, for example, you can see that here an instance of a data frame is created and named as “myTable” by using the command data.frame() and this creates an empty data frame. 

myTable = data.frame() 
 

Step 2: Next we will use the edit function to launch the viewer. Note that “myTable” data frame is passed back to the “myTable” object and this way the changes we make to this module will be saved to the original object. 

myTable = edit(myTable) 
 

So, when the above command is executed it will pop up a window like this, 

Step 3: Now, the table is completed with this small roster.  

Note that, change variable names by clicking on their labels and typing your changes. Variables can also be set as numeric or character. Once the data in the DataFrame looks like the above, close the table. Changes are saved automatically.

Step 4: Check out the resulting data frame by printing it.  

> myTable 
 

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

Adding rows and columns to the data frame

Adding extra rows: We can add extra row using the command rbind(). The syntax for this is given below,  

newDF = rbind(df, the entries for the new row you have to add )
df = Original data frame 
 

Note that the entries for the new row you have to add you have to be careful when using rbind() because the data types in each column entry should be equal to the data types that are already existing rows. 

Example:  

Python3




# R program to illustrate operation on a data frame
 
# Creating a dataframe
df = data.frame(
  "Name" = c("Amiya", "Raj", "Asish"),
  "Language" = c("R", "Python", "Java"),
  "Age" = c(22, 25, 45)
)
cat("Before adding row\n")
print(df)
 
# Add a new row using rbind()
newDf = rbind(df, data.frame(Name = "Sandeep",
                            Language = "C",
                            Age = 23
                           ))
cat("After Added a row\n")
print(newDf)


Output: 

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

After Added a row
     Name Language Age
1   Amiya        R  22
2     Raj   Python  25
3   Asish     Java  45
4 Sandeep        C  23

Adding extra columns: We can add extra column using the command cbind(). The syntax for this is given below,  

newDF = cbind(df, the entries for the new column you have to add )
df = Original data frame 
 

Example:  

Python3




# R program to illustrate operation on a data frame
 
# Creating a dataframe
df = data.frame(
  "Name" = c("Amiya", "Raj", "Asish"),
  "Language" = c("R", "Python", "Java"),
  "Age" = c(22, 25, 45)
)
cat("Before adding column\n")
print(df)
 
# Add a new column using cbind()
newDf = cbind(df, Rank=c(3, 5, 1))
 
cat("After Added a column\n")
print(newDf)


Output: 

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

After Added a column
   Name Language Age Rank
1 Amiya        R  22    3
2   Raj   Python  25    5
3 Asish     Java  45    1

Adding new variables to DataFrame

In R, we can add new variables to a data frame based on existing ones. To do that we have to first call the dplyr library using the command library() . And then calling mutate() function will add extra variable columns based on existing ones. 

Syntax:  

library(dplyr) 
newDF = mutate(df, new_var=[existing_var])
df = original data frame 
new_var = Name of the new variable 
existing_var = The modify action you are taking(e.g log value, multiply by 10) 
 

Example:  

Python3




# R program to illustrate operation on a data frame
 
# Importing the dplyr library
library(dplyr)
 
# Creating a dataframe
df = data.frame(
  "Name" = c("Amiya", "Raj", "Asish"),
  "Language" = c("R", "Python", "Java"),
  "Age" = c(22, 25, 45)
)
cat("Original Dataframe\n")
print(df)
 
# Creating an extra variable column
# "log_Age" which is log of variable column "Age"
# Using mutate() command
newDf = mutate(df, log_Age = log(Age))
 
cat("After creating extra variable column\n")
print(newDf)


Output: 

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

After creating extra variable column
   Name Language Age  log_Age
1 Amiya        R  22 3.091042
2   Raj   Python  25 3.218876
3 Asish     Java  45 3.806662

Deleting rows and columns from a data frame

To delete a row or a column, first of all, you need to access that row or column and then insert a negative sign before that row or column. It indicates that you had to delete that row or column. 

Syntax:  

newDF = df[-rowNo, -colNo]
df = original data frame 
 

Example:  

Python3




# R program to illustrate operation on a data frame
 
# Creating a dataframe
df = data.frame(
  "Name" = c("Amiya", "Raj", "Asish"),
  "Language" = c("R", "Python", "Java"),
  "Age" = c(22, 25, 45)
)
cat("Before deleting the 3rd row and 2nd column\n")
print(df)
 
# delete the third row and the second column
newDF = df[-3, -2]
 
cat("After Deleted the 3rd row and 2nd column\n")
print(newDF)


Output: 

Before deleting the 3rd row and 2nd column
   Name Language Age
1 Amiya        R  22
2   Raj   Python  25
3 Asish     Java  45
After Deleted the 3rd row and 2nd column
   Name Age
1 Amiya  22
2   Raj  25

 



Similar Reads

R - Create Dataframe From Existing Dataframe
Create Dataframes when dealing with organized data so sometimes we also need to make Dataframes from already existing Dataframes. In this Article, let's explore various ways to create a data frame from an existing data frame in R Programming Language. Ways to Create Dataframe from Existing Dataframe Using Base R data. frame() FunctionUsing subset()
6 min read
How to standardized a column of R DataFrame ?
A large dataset that had multiple columns with varying ranges and units may need to be standardized before further processing. In this article, we will be discussing how to standardize a column of dataframe in R Programming Language. Let's first discuss standardization. Standardization is a feature scaling technique. It is the process of rescaling
3 min read
How to convert excel content into DataFrame in R ?
R Programming Language allows us to read and write data into various files like CSV, Excel, XML, etc. In this article, we are going to discuss how to convert excel content into DataFrame in R Programming. To read an excel file itself, read.xlsx() function from xlsx is used. Installation This module is not built into R but it can be installed and im
2 min read
Matrix vs Dataframe in R
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.The two most important data structures in R are Matrix and Dataframe, they look the same but different in nature. Matrix in R - It's a homogeneous collection of data sets
3 min read
R - DataFrame Manipulation
Data Frame is a two-dimensional structured entity consisting of rows and columns. It consists equal length vectors as rows. The data is stored in cells which are accessed by specifying the corresponding [row, col] set of values of the data frame. Manipulation of data frames involve modifying, extracting and restructuring the contents of a data fram
9 min read
Reorder the column of dataframe in R using Dplyr
In this article, we will discuss how to rearrange or reorder the column of the dataframe using dplyr package in R Programming Language. Creating Dataframe for demonstration: C/C++ Code # load the package library(dplyr) # create the dataframe with three columns # id , department and salary with 8 rows data = data.frame(id = c(7058, 7059, 7060, 7089,
4 min read
The Factor Issue in a DataFrame in R Programming
DataFrames are generic data objects of R which are used to store the tabular data. Data frames are considered to be the most popular data objects in R programming because it is more comfortable to analyze the data in the tabular form. Data frames can also be taught as matrices where each column of a matrix can be of the different data types. Factor
4 min read
How to find maximum string length by column in R DataFrame ?
In this article, we are going to see how to find maximum string length by column in R Programming Language. To find the maximum string length by column in the given dataframe, first, nchar() function is called to get the length of all the string present in the particular column of the dataframe, and then the max() function must be called to get the
2 min read
Change column name of a given DataFrame in R
A data frame is a tabular structure with fixed dimensions, of each rows as well as columns. It is a two-dimensional array like object with numerical, character based or factor-type data. Each element belonging to the data frame is indexed by a unique combination of the row and column number respectively. Column names are addressed by unique names.
5 min read
Change more than one column name of a given DataFrame in R
A data frame is a tabular structure with fixed dimensions, of each row as well as columns. It is a two-dimensional array-like object with numerical, character-based, or factor-type data. Each element belonging to the data frame is indexed by a unique combination of the row and column number respectively. Column names are addressed by unique names.
4 min read
Convert DataFrame to vector in R
In this article, we will discuss how a dataframe can be converted to a vector in R. For the Conversion of dataframe into a vector, we can simply pass the dataframe column name as [[index]]. Approach: We are taking a column in the dataframe and passing it into another variable by the selection method. Selection method can be defined as choosing a co
2 min read
Extract last N rows of dataframe in R
The last n rows of the data frame can be accessed by using the in-built tail() method in R. Supposedly, N is the total number of rows in the data frame, then n <=N last rows can be extracted from the structure. Syntax: tail(dataframe, n = ) Parameter : dataframe - The data frame to extract rows from the endn - integer which indicates the number
3 min read
How to Export DataFrame to CSV in R ?
R Programming language allows us to read and write data into various files like CSV, Excel, XML, etc. In this article, we are going to discuss how to Export DataFrame to CSV file in R Programming Language. Approach: Write Data in column wise formatCreate DataFrame for these dataWrite Data to the CSV filePrint the success message Function used: data
1 min read
Create table from DataFrame in R
In this article, we are going to discuss how to create a table from the given Data-Frame in the R Programming language. Function Used: table(): This function is an essential function for performing interactive data analyses. As it simply creates tabular results of categorical variables. Syntax: table(…, exclude = if (useNA == "no") c(NA, NaN),useNA
3 min read
Create a correlation matrix from a DataFrame of same data type in R
A correlation matrix is a type of table showing correlation coefficients between variables. Here, each cell in the table shows the correlation between two variables. This matrix is used correlation matrix is used to summarize data. In this article we, will be looking at the approach to get the correlation matrix from a given DataFrame of the same d
2 min read
How to find group-wise summary statistics for R dataframe?
Finding group-wise summary statistics for the dataframe is very useful in understanding our data frame. The summary includes statistical data: mean, median, min, max, and quartiles of the given dataframe. The summary can be computed on a single column or variable, or the entire dataframe. In this article, we are going to see how to find group-wise
4 min read
How to export a DataFrame to Excel File in R ?
It is a frequent requirement to save our dataframe for portability after working on it on the auxiliary memory of the computer system using R Programming Language. In this article, we will be using writexl package to export our dataframe to excel(.xlsx). The write_xlsx() function of the writexl package is used to export our dataframe to an Excel fi
3 min read
How to Replace particular value in R dataframe ?
Often, some values in our dataframe are not appropriate, they are not up-to-date, or we aren't aware of those values. In such cases, we replace those values, because they are causing ambiguity. Over here, we will use the term NA, which stands for Non-Available to replace the unknown values. In this article, we will see how to change or replace all
4 min read
Convert dataframe to data.table in R
In this article, we will discuss how to convert dataframe to data.table in R Programming Language. data.table is an R package that provides an enhanced version of dataframe. Characteristics of data.table : data.table doesn’t set or use row namesrow numbers are printed with a : for better readabilityUnlike dataframes, columns of character type are n
5 min read
How to plot a subset of a dataframe using ggplot2 in R ?
In this article, we will discuss plotting a subset of a data frame using ggplot2 in the R programming language. Dataframe in use: AgeScoreEnrollNo117700521880103177915419752051885256199630717903581971409188345 To get a complete picture, let us first draw a complete data frame. Example: C/C++ Code # Load ggplot2 package library(ggplot2) # Create Dat
8 min read
How to append a whole dataframe to a CSV in R ?
A data frame in R programming language is a tabular arrangement of rows and columns arranged in the form of a table. A CSV file also contains data stored together to form rows stacked together. Content can be read from and written to the CSV file. Base R contains multiple methods to work with these files. The write.csv() method overwrites the entir
3 min read
Combine two ggplot2 plots from different DataFrame in R
In this article, we are going to learn how to Combine two ggplot2 plots from different DataFrame in R Programming Language. Here in this article we are using a scatter plot, but it can be applied to any other plot. Let us first individually draw two ggplot2 Scatter Plots by different DataFrames then we will see how to combine them i.e how draw both
2 min read
How to plot all the columns of a dataframe in R ?
In this article, we will learn how to plot all columns of the DataFrame in R programming language. Dataset in use: x y1 y2 y3 1 1 0.08475635 0.4543649 0 2 2 0.22646034 0.6492529 1 3 3 0.43255650 0.1537271 0 4 4 0.55806524 0.6492887 3 5 5 0.05975527 0.3832137 1 6 6 0.08475635 0.4543649 0 7 7 0.22646034 0.6492529 1 8 8 0.43255650 0.1537271 0 9 9 0.55
5 min read
Combine Multiple Excel Worksheets into Single Dataframe in R
In this article, we will discuss how to combine multiple excel worksheets into a single dataframe in R Programming Language. The below XLSX file "gfg.xlsx" has been used for all the different approaches. Method 1: Using readxl package The inbuilt setwd() method is used to set the working directory in R. The readxl package in R is used to import and
4 min read
How to plot a subset of a dataframe in R ?
In this article, we will learn multiple approaches to plotting a subset of a Dataframe in R Programming Language. Here we will be using, R language's inbuilt "USArrests" dataset. Method 1: Using subset() function In this method, first a subset of the data is created base don some condition, and then it is plotted using plot function. Let us first c
2 min read
Sorting DataFrame in R using Dplyr
In this article, we will discuss about how to sort a dataframe in R programming language using Dplyr package. The package Dplyr in R programming language provides a function called arrange() function which is useful for sorting the dataframe. Syntax : arrange(.data, ...) The methods given below show how this function can be used in various ways to
3 min read
Write DataFrame to SPSS .sav File in R
In this article, we are going to see how to write Dataframe to SPSS .sav File in R Programming language. The SPSS Statistics File Format is a proprietary binary format, developed and maintained as the native format for the SPSS statistical software application. To write a data frame in SPSS format in R we use the write_sav() function of the haven p
1 min read
Numbering Rows within Groups of DataFrame in R
In this article, we will discuss how to number rows within the group of the dataframe in the R programming language Method 1: Using ave() function Call the ave() function, which is a base function of the R language, and pass the required parameters to this function and this process will be leading to the numbering rows within the group of the given
2 min read
Insert Rows for Missing Dates in R DataFrame
In this article, we are going to see how to insert rows for missing dates in R Programming language. The padr package in R is used to make preparations of time series data using the pad() function. The package can be downloaded and installed into the working space using the following command : install.packages(“padr”) The pad method in R is used to
2 min read
Subset Dataframe Rows Based On Factor Levels in R
In this article, we will be discussing how to subset a given dataframe rows based on different factor levels with the help of some operators in the R programming language. Method 1: Subset dataframe Rows Based On One Factor Levels In this approach to subset dataframe rows based on one-factor levels, the user just needs the in-built operator of the
2 min read