How to Append Rows to a Data Frame in R (With Examples)

Appending rows to a data frame is a common task in R. This can be done using a variety of methods such as using the rbind() function or the merge() function. The rbind() function is used to add rows to an existing data frame while the merge() function is used to merge two data frames based on common columns or row names. Examples are provided to illustrate the use of these functions.


You can quickly append one or more rows to a data frame in R by using one of the following methods:

Method 1: Use rbind() to append data frames.

rbind(df1, df2)

Method 2: Use nrow() to append a row.

df[nrow(df) + 1,] = c(value1, value2, ...)

This tutorial provides examples of how to use each of these methods in practice.

Method 1: Use rbind() to Append Data Frames

This first method assumes that you have two data frames with the same column names. By using the rbind() function, we can easily append the rows of the second data frame to the end of the first data frame.

For example:

#define data frame
df1 <- data.frame(var1=c(4, 13, 7, 8),
                  var2=c(15, 9, 9, 13),
                  var3=c(12, 12, 7, 5))
df1

  var1 var2 var3
1    4   15   12
2   13    9   12
3    7    9    7
4    8   13    5

#define second data frame
df2 <- data.frame(var1=c(4, 13),
                  var2=c(9, 12),
                  var3=c(6, 6))
df2

  var1 var2 var3
1    4    9    6
2   13   12    6

#append the rows of the second data frame to end of first data frame
df3 <- rbind(df1, df2)
df3

  var1 var2 var3
1    4   15   12
2   13    9   12
3    7    9    7
4    8   13    5
5    4    9    6
6   13   12    6

Method 2: Use nrow() to Append a Row 

This method uses the nrow() function to append a row to the end of a given data frame.

For example:

#define first data frame
df1 <- data.frame(var1=c(4, 13, 7, 8),
                  var2=c(15, 9, 9, 13),
                  var3=c(12, 12, 7, 5))
df1

  var1 var2 var3
1    4   15   12
2   13    9   12
3    7    9    7
4    8   13    5

#append row to end of data frame 
df1[nrow(df1) + 1,] = c(5, 5, 3)
df1

  var1 var2 var3
1    4   15   12
2   13    9   12
3    7    9    7
4    8   13    5
5    5    5    3

In order for this method to work, the vector of values that you’re appending needs to be the same length as the number of columns in the data frame.

How to Create an Empty Data Frame in R
How to Loop Through Column Names in R
How to Add an Index Column to a Data Frame in R

x