R – DataFrame Manipulation
Last Updated :
21 Apr, 2020
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 frame. In this article, we will study about the various operations concerned with the manipulation of data frames in R.
Renaming columns
Columns of a data frame can be renamed to set new names as labels. However, the changes are not reflected in the original data frame. Not all the columns have to be renamed. The column labels may be set to complex numbers, numerical or string values. The time complexity required to rename all the columns is O(c) where c is the number of columns in the data frame. There are two ways to rename columns in a Data Frame:
rename() function of the plyr package
The rename() function of the plyr package modifies the names of the columns based on the old names. It does not take column positions as arguments to rename the column labels.
Examples:
df <- library(plyr)
df<-data.frame(row1 = 0:2, row2 = 3:5, row3 = 6:8)
print("Original Data Frame")
print(df)
print("Modified Data Frame")
rename(df, c("row1"="one", "row2"="two", "row3"="three"))
|
Output:
[1] "Original Data Frame"
row1 row2 row3
1 0 3 6
2 1 4 7
3 2 5 8
[1] "Modified Data Frame"
one two three
1 0 3 6
2 1 4 7
3 2 5 8
The column labels are changed. In this case, the result has to be assigned back to the data frame, in order to retain the changes.
- R’s in-built function: names(data frame)[col]
The column labels can be renamed either using the column index or column name to set the new values. The changes are reflected in the original data frame. names() function allows us to change the label of a single column at a time.
Example 1:
df<-data.frame(row1 = 0:2, row2 = 3:5, row3 = 6:8)
print("Original Data Frame")
print(df)
print("Modified Data Frame")
names(df)[names(df)=="row3"]<-"three"
print(df)
|
Output:
[1] "Original Data Frame"
row1 row2 row3
1 0 3 6
2 1 4 7
3 2 5 8
[1] "Modified Data Frame"
row1 row2 three
1 0 3 6
2 1 4 7
3 2 5 8
Here, the label of third column is modified from row3 to three. The changes are retained in the original database.
Example 2:
df<-data.frame(row1 = 0:2, row2 = 3:5, row3 = 6:8)
print("Original Data Frame")
print(df)
print("Modified Data Frame")
names(df)[2]<-"two"
print(df)
|
Output:
[1] "Original Data Frame"
row1 row2 row3
1 0 3 6
2 1 4 7
3 2 5 8
[1] "Modified Data Frame"
row1 two row3
1 0 3 6
2 1 4 7
3 2 5 8
Here, the second column label is changed to two from row2.The changes are retained in the original database.
Expanding Data Frame
The data frames can both be expanded further to aggregate more columns or contracted to delete columns.
- Adding columns to a data frame
The columns, in the form of vectors can be added using data frame indexing modes. The new column is appended at the end of the data frame. The values in new columns may even be a combination of two existing columns, for instance, the addition or subtraction of two columns. A column consisting of NA values can also be appended. Changes are retained in the original data frame. The time complexity required to add column is O(n) where n is the number of rows of the data frame. There are various ways to add new column.
Syntax:
dataframe[[newcol]] <- vector
or
dataframe[newcol] <-vector
or
dataframe$newcol <-vector
Example:
df<-data.frame(col1 = 0:2, col2 = 3:5, col3 = 6:8)
print ("Original Data Frame")
print (df)
df[["col4"]]<-0
df$"col5"<-NA
df[["col5"]] <- df[["col1"]] + df[["col2"]]
print ("Modified Data Frame")
print (df)
|
Output:
[1] "Original Data Frame"
col1 col2 col3
1 0 3 6
2 1 4 7
3 2 5 8
[1] "Modified Data Frame"
col1 col2 col3 col4 col5
1 0 3 6 0 3
2 1 4 7 0 5
3 2 5 8 0 7
The entire col4 is assigned a value of vector zero and added at the end in the data frame, first. Then the fifth column is created which is accessed using df$col5, and assigned a value of NA. The corresponding values are then recomputed as a sum of elements of columns 1 and 2.
- Removing columns from a data frame
The columns of a data frame can be dropped from the data frame by either their names or index values. Multiple columns can be deleted together from the data frame. The desired column name or index can be assigned to a NULL value, and accordingly the columns are shifted. The columns are then reduced by the number of the deletions. The changes are reflected in the original data frame.
Example 1:
df<-data.frame(row1 = 0:2, row2 = 3:5, row3 = 6:8)
print ("Original Data Frame")
print (df)
df[["row2"]]<-NULL
print(df)
|
Output:
[1] "Original Data Frame"
row1 row2 row3
1 0 3 6
2 1 4 7
3 2 5 8
row1 row3
1 0 6
2 1 7
3 2 8
row2 is deleted from the data frame. The column labels remain the same. df[row2]<-NULL would also produce a similar result.
Example 2: Delete the columns by integer indexing of the columns
df<-data.frame(row1 = 0:2, row2 = 3:5, row3 = 6:8, row4 = rep(5))
print ("Original Data Frame")
print (df)
df <- df [-c(1, 3)]
print(df)
|
Output:
[1] "Original Data Frame"
row1 row2 row3 row4
1 0 3 6 5
2 1 4 7 5
3 2 5 8 5
row2 row4
1 3 5
2 4 5
3 5 5
The columns to be excluded are specified using a vector -c(..column indices..). Here the columns 1 and 3 are deleted from the data frame, while the changes are still retained in the original data frame.
Subsetting a data frame
subset() function can be used, where the select argument involves the column names to be dropped from a data frame.Multiple column names can also be specified by converting them to a vector c(col1, col2). This operation creates two disjoint sets of the data frame, one with the excluded columns and other with the included columns. The number of columns get reduced by the number of deletions. Changes do reflect in the original data frame.
Syntax:
subset(dataframe, select= - column)
Example:
df<-data.frame(row1 = 0:2, row2 = 3:5, row3 = 6:8)
print ("Original Data Frame")
print (df)
df<-subset(df, select = - c(row1, row2))
print("Modified Data Frame")
print(df)
|
Output:
[1] "Original Data Frame"
row1 row2 row3
1 0 3 6
2 1 4 7
3 2 5 8
[1] "Modified Data Frame"
row3
1 6
2 7
3 8
Here, row1 and row2 both are removed from the data frame. Hence, this subset contains just one column of the original set of columns.
Reordering columns
Columns of a data frame can be re-ordered by either specifying the column names or column indices in the desired order. The original data frame remains the same. The changes have to be assigned back to retain the ordering. The time complexity required to reorder the columns in worst case is O(m*n) where all the elements have to be shifted to a new position, with m being the number of rows and n being the number of columns.
Example 1:
df<-data.frame(row1 = 0:2, row2 = 3:5, row3 = 6:8)
print("Original Data Frame")
print(df)
print("Modified Data Frame")
df[,c(2, 1, 3)]
|
Output:
[1] "Original Data Frame"
row1 row2 row3
1 0 3 6
2 1 4 7
3 2 5 8
[1] "Modified Data Frame"
row2 row1 row3
1 3 0 6
2 4 1 7
3 5 2 8
Here, the desired order is specified as column indices. Therefore, the columns are reordered to column indices[2, 1, 3]. Changes are not made to the original data frame.
Example 2:
df<-data.frame(row1 = 0:2, row2 = 3:5, row3 = 6:8)
print("Original Data Frame")
print(df)
print("Modified Data Frame")
df <- df[c(2, 1, 3)]
print(df)
|
Output:
[1] "Original Data Frame"
row1 row2 row3
1 0 3 6
2 1 4 7
3 2 5 8
[1] "Modified Data Frame"
row2 row1 row3
1 3 0 6
2 4 1 7
3 5 2 8
Here, the desired order is specified as column names. Changes are made to original data frame.
Get 90% Course fee refund on completing 90% course in 90 days! Take the Three 90 Challenge today.
The next 90 Days of focus & determination can unlock your full potential. The Three 90 challenge has started and this is your chance to upskill and get 90% refund. What more motivation do you need? Start the challenge right away!
Similar Reads
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, extrac
9 min read
DataFrame Operations in R
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
9 min read
Manipulate R Data Frames Using SQL
Manipulating data frames in R Programming using SQL can be easily done using the sqldf package. This package in R provides a mechanism that allows data frame manipulation with SQL and also helps to connect with a limited number of databases. The sqldf package in R is basically used for executing the
8 min read
Manipulating DataFrames with Pandas - Python
Before manipulating the dataframe with pandas we have to understand what is data manipulation. The data in the real world is very unpleasant & unordered so by performing certain operations we can make data understandable based on one's requirements, this process of converting unordered data into
4 min read
List of Dataframes in R
DataFrames are generic data objects of R which are used to store the tabular data. They are two-dimensional, heterogeneous data structures. A list in R, however, comprises of elements, vectors, data frames, variables, or lists that may belong to different data types. In this article, we will study h
8 min read
Julia - DataFrames
Data Frames in Julia is an alternative for Pandas Package in Python. Data Frames represent the data in a tabular structure. We can manipulate the data using these data frames. Various operations can be done on the Data frames for altering the data and making row-column transformations. Data Frames a
5 min read
Data Manipulation in R with Dplyr Package
In this article let's discuss manipulating data in the R programming language. In order to manipulate the data, R provides a library called dplyr which consists of many built-in methods to manipulate the data. So to use the data manipulation function, first need to import the dplyr package using lib
5 min read
how to expand dataframe in r
In this article, we will discuss how to expand the data frame in R Programming Language. Now create a Data Frame of all the Combinations of Vectors passed as Arguments in R Programming using expand.grid() Function. expand.grid() Functionexpand.grid() function in R Programming Language is used to cre
2 min read
How to Delete DataFrames in R?
In this article, we will discuss how to delete Dataframes in R Programming Language. A DataFrame is a two-dimensional data structure that can store data in rows and columns, we can create a dataframe by using data.frame() function Create Dataframe for demonstration: C/C++ Code # dataframe1 data1 = d
2 min read
R - Data Frames
R Programming Language is an open-source programming language that is widely used as a statistical software and data analysis tool. Data Frames in R Language are generic data objects of R that are used to store tabular data. Data frames can also be interpreted as matrices where each column of a matr
10 min read
DataFrame Row Slice in R
In this article, we are going to see how to Slice row in Dataframe using R Programming Language. Row slicing in R is a way to access the data frame rows and further use them for operations or methods. The rows can be accessed in any possible order and stored in other vectors or matrices as well. Row
4 min read
R Read Text File to DataFrame
In today's data-driven world, collecting data from multiple sources and turning it into a structured manner is a critical responsibility for data analysts and scientists. Text files are a prominent source of data, as they frequently include useful information in plain text format. To be used success
5 min read
How to Handle Error in data.frame in R
In R programming Language, the data.frame() method plays a crucial role in organizing and handling data in a dynamic setting. But things don't always go as planned, and mistakes do happen. This post acts as a manual for comprehending typical mistakes in the data.frame() method and offers helpful adv
3 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
3 min read
Plot columns from list of dataframes in R
In this article, we will discuss how to plot columns from a list of dataframes in R programming language. Note: We are taking a line plot for implementation same can be applied to any other plot. The ggplot() method is supplemented by different geometrical shapes to indicate the type of data plottin
2 min read
How to create dataframe in R
Dataframes are fundamental data structures in R for storing and manipulating data in tabular form. They allow you to organize data into rows and columns, similar to a spreadsheet or a database table. Creating a data frame in the R Programming Language is a simple yet essential task for data analysis
3 min read
How to merge dataframes in R ?
In this article, we will discuss how to perform inner, outer, left, or right joins in a given dataframe in R Programming Language. Functions Used merge() function is used to merge or join two tables. With appropriate values provided to specific parameters, we can create the desired join. Syntax: mer
3 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
2 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: tabl
3 min read