How to add rows to R Data frame (with 7 code examples)

by SkillAiNest

In this tutorial, we will cover how to add to the data frame in the R – one of the most common modifications on a data frame.

A data frame is one of the essential data structures in programming language. It is considered very flexible because it can contain many types of data and is easy to edit. One of the most common modifications on the data frame in R is to add new observations (rows) to it.

In this tutorial, we will discuss different ways to put one or more rows in a data frame in R. If you are new to making a data frame in R, you want to read how to make a data frame in the R before continuing this post.

Before starting, let’s create a simple data frame as an experience:

super_sleepers_initial <- data.frame(animal=c('koala', 'hedgehog'), 
                                     country=c('Australia', 'Italy'),
                                     avg_sleep_hours=c(21, 18), 
                                     stringsAsFactors=FALSE)
print(super_sleepers_initial)
AnimalCountryavg_sleep_hours
1HoodAustralia21
2HedgehogItaly18

Note: When creating the above data frame, we added the optional parameter stringsAsFactors=FALSE. While as default it is parameter TRUEIn the majority cases (unless we have a character data type column), that is Strictly recommended To set it FALSE Avoid suppressing the role of the character in the factor data type and therefore unwanted side effects. As an experiment, you can remove this parameter from the above piece of code, run it and then run the cells and observe the consequences.

Adding the same row to the data frame in R

Using rbind()

Add a row to the data frame in R, we can use rbind() Built -in function, which means “rowing”. The basic syntax is as follows:

dataframe <- rbind(dataframe, new_row)

Note that in the aforementioned syntax, by new_row We will probably understand a List Instead of a VisitUnless all the columns of our data frame are of the same data type (which is often not the case).

Let’s re -create a new data frame super_sleepers From the initial one super_sleepers_initial And add another row to it:

# Reconstructing the super_sleepers dataframe
super_sleepers <- super_sleepers_initial

super_sleepers <- rbind(super_sleepers, list('sloth', 'Peru', 17))
print(super_sleepers)
AnimalCountryavg_sleep_hours
1HoodAustralia21
2HedgehogItaly18
3LowlyVeil17

The new row was added at the end of the data frame.

It is important to keep in mind that in all examples here and after, the new row (or rows) must reflect the structure of the data frame from which it has been added, which means that the length of the list should be equal to the number of columns in the data frame, and the information of the information on the list should be the data. In the opposite case, the program will throw a mistake.

Using nrow()

Another way to add a row to a R data frame is to use it nrow() The function syntax is as follows:

dataframe(nrow(dataframe) + 1,) <- new_row

This syntax literally means that we calculate the number of rows in the data frame (nrow(dataframe)), Add 1 to this number (nrow(dataframe) + 1), And then add a new row new_row On this index of data frame (dataframe(nrow(dataframe) + 1,)) – That is, as a new last row.

Exactly like before, our new_row Probably have to be one List Instead of a VisitUnless all the data frame columns are of the same data type, which is not common.

Let’s add another “super -sleeper” to our table:

super_sleepers(nrow(super_sleepers) + 1,) <- list('panda', 'China', 10)
print(super_sleepers)
AnimalCountryavg_sleep_hours
1HoodAustralia21
2HedgehogItaly18
3LowlyVeil17
4PandaChina10

Once again, the new row was added by the end of the data frame.

Using add_row() Injured tidyverse

What will happen, instead, we want to add a new row to a particular index, not at the end of the data frame? For example, we found that Tigers sleep 16 hours a day, (ie more than pandas in our rankings, so we need to enter this observation as the last row of the data frame). In this case, the use of the base r is not enough, but we can use add_row() The job of tidyverse R package (we may need to install it, if it’s not yet installed, running, running install.packages("tidyverse")::

library(tidyverse)
super_sleepers <- super_sleepers 
                                             country='India', 
                                             avg_sleep_hours=16, 
                                             .before=4)
print(super_sleepers)
AnimalCountryavg_sleep_hours
1HoodAustralia21
2HedgehogItaly18
3LowlyVeil17
4LionIndia16
5PandaChina10

Here, we should note the following:

  • We passed the same names of the columns in the same order as in the current data frame and assigned them to new values.
  • After this setting, we added .before Explain the optional parameter and the necessary index. If we do not do so, the row will be added as a default at the end of the data frame. As alternatives, we can use .after Optional parameter and assign it an index of row After Which is to enter a new observation.
  • We used the assignment operator <- To save the existing data frame to save amendments.

Adding multiple rows to R data frame

Using rbind()

Often, we need to add not one but multiple rows to the R data frame. Here is the easiest way to use here rbind() The function more clearly, in this case, we need to combine the two data frames in practice: the initial one and the one that is in the row.

dataframe_1 <- rbind(dataframe_1, dataframe_2)

To see how it works, let’s create a new data frame super_sleepers From the initial one super_sleepers_initialPrint to remember what it looks like, and add two new rows to the end of it:

# Reconstructing the super_sleepers dataframe
super_sleepers <- super_sleepers_initial
print(super_sleepers)
cat('\n\n')  # printing an empty line

# Creating a new dataframe with the necessary rows
super_sleepers_2 <- data.frame(animal=c('squirrel', 'panda'), 
                               country=c('Canada', 'China'),
                               avg_sleep_hours=c(15, 10), 
                               stringsAsFactors=FALSE)

# Appending the rows of the new dataframe to the end of the existing one
super_sleepers <- rbind(super_sleepers, super_sleepers_2)
print(super_sleepers)
AnimalCountryavg_sleep_hours
1HoodAustralia21
2HedgehogItaly18
AnimalCountryavg_sleep_hours
1HoodAustralia21
2HedgehogItaly18
3SquirrelCanada15
4LionIndia16

As a reminder, the new rows should reflect the structure of the data frame in which they have been added, which means that both data films, column names, their succession and data types will be the same.

Using nrow()

As alternatives, we can use nrow() Function to add numerous rows to the data frame in R. However, here’s the point of view Have not been recommended Because syntax is very clumsy and difficult to read. In fact, in this case, we need to calculate the start and end index. We have to be very much manipulated with it, we nrow() The function technically, the syntax is as follows:

dataframe_1((nrow(dataframe_1) + 1):(nrow(dataframe_1) + nrow(dataframe_2)),) <- dataframe_2

Let’s make our formation super_sleepers By super_sleepers_initial And add the rows of the already existing data frame super_sleepers_2:

# Reconstructing the super_sleepers dataframe
super_sleepers <- super_sleepers_initial

super_sleepers((nrow(super_sleepers) + 1):(nrow(super_sleepers) + nrow(super_sleepers_2)),) <- super_sleepers_2
print(super_sleepers)
AnimalCountryavg_sleep_hours
1HoodAustralia21
2HedgehogItaly18
3SquirrelCanada15
4PandaChina10

We got the same data frame as the previous example and observed that the previous approach is very beautiful.

Using add_row() Injured tidyverse

Finally, we can use again add_row() The job of tidyverse The package is more flexible because we can either add new rows at the end of the existing data frame or insert before/after a particular row prescribed by its index.

Let’s enter the existing data frames for the sluggish and tiger between the hedgehog and the squirrel super_sleepers:

library(tidyverse)
super_sleepers <- super_sleepers 
                                             country=c('Peru', 'India'),
                                             avg_sleep_hours=c(17, 16), 
                                             .before=3)
print(super_sleepers)
AnimalCountryavg_sleep_hours
1HoodAustralia21
2HedgehogItaly18
3LowlyVeil17
4LionIndia16
5SquirrelCanada15
6PandaChina10

Note that we can use the above results, we can use .after=2 Instead of .before=3.

Conclusion

In this tutorial, we learned how to add the same row (or multiple rows) to the data frame in R – or how to enter it (or that) on a specific index of the data frame. Specifically, we considered 3 points: using rbind() Or nrow() Twenty r functions, or add_row() The job of tidyverse R package we have paid special attention to the best use and nuances for each method that have to be taken into account in different situations.

If you would like to find out more about working with data fames in R, check how to add columns to the data frame in R (with 18 code examples)

You may also like

Leave a Comment

At Skillainest, we believe the future belongs to those who embrace AI, upgrade their skills, and stay ahead of the curve.

Get latest news

Subscribe my Newsletter for new blog posts, tips & new photos. Let's stay updated!

@2025 Skillainest.Designed and Developed by Pro