How can I append rows to a data frame in R? Can you provide some examples?

Appending rows to a data frame in R refers to the process of adding new observations or data points to an existing data frame. This can be done using the “rbind()” function, which combines rows from one or more data frames and creates a new data frame. This function takes in two arguments, the first being the original data frame and the second being the new rows to be added. The new rows must be in the same format and have the same column names as the original data frame. Some examples of using the “rbind()” function to append rows to a data frame in R are: adding a new row of data collected from a survey, including new data from a different source, or combining multiple data frames with similar data into one larger data frame.

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


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.

Additional Resources

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