6.2 C
London
Thursday, December 19, 2024
HomeStatistics TutorialRHow to Append Rows to a Data Frame in R (With Examples)

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

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories