Open In App

How to append rows to R DataFrame ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, let’s discuss how to append rows to DataFrame in R Programming Language. There are various ways to append rows to an R data frame : 

Method 1: Using rbind()

A row can be defined using a vector of values and appended to the data frame using the rbind() method, which essentially means row binding. This method can be used to combine two vectors, a dataframe, and a vector, and even two or more data frames also. In order to preserve the changes, the output has to be assigned to the original or modified data frame. The number of rows, in this case, increases by one. The rbind() method has the following syntax : 

Syntax: rbind(x,x1)

Arguments : x and x1 are the objects to combine 

Return: combined data frame formed from x and x1

Example:

R




# declaring a data frame in R
data_frame = data.frame(C1 = c(1:4),
                        C2 = c(5:8),
                        C3 = c(9:12),
                        C4 = c(13:16))
  
print("Original data frame")
print(data_frame)
  
# defining new row data frame
new_row = c("New","Row","Added","Dataframe")
  
# bind a new row to the original data frame
data_frame <- rbind(data_frame,new_row)
print ("Modified Data Frame")
print(data_frame)


Output:

[1] "Original data frame"
 C1 C2 C3 C4
1  1  5  9 13
2  2  6 10 14
3  3  7 11 15
4  4  8 12 16
[1] "Modified Data Frame"
  C1  C2    C3        C4
1   1   5     9        13
2   2   6    10        14
3   3   7    11        15
4   4   8    12        16
5 New Row Added Dataframe

Method 2: 

We can calculate the number of rows in a data frame and then append a new row at the index (number of rows + 1). The new row can be defined in the form of a vector of values. The modification made is preserved to the data frame. The time complexity incurred in this method is linear in terms of the row size. The following code snippet indicates the usage of this method : 

R




# declaring a data frame in R
data_frame = data.frame(C1 = c(1:4),
                        C2 = c( 5:8), 
                        C3 = c(9:12),
                        C4 = c(13:16))
  
print("Original data frame")
print(data_frame)
  
# calculating number of rows in data frame
num_rows = nrow(data_frame)
  
# defining new row data frame
new_row = c("New","Row","Added","Dataframe")
  
# assigning the new row at a new
# index after the original number of rows 
data_frame[num_rows + 1,] = new_row
print ("Modified Data Frame")
print(data_frame)


Output:

[1] "Original data frame"
 C1 C2 C3 C4
1  1  5  9 13
2  2  6 10 14
3  3  7 11 15
4  4  8 12 16
[1] "Modified Data Frame"
  C1  C2    C3        C4
1   1   5     9        13
2   2   6    10        14
3   3   7    11        15
4   4   8    12        16
5 New Row Added Dataframe


Last Updated : 07 Apr, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads