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 #define second data frame
df2 #append the rows of the second data frame to end of first data frame
df3
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 #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