In this tutorial, we will look at how to add a row to an existing dataframe in R with the help of some examples.
How do I add a row to a dataframe in R?
You can use the rbind()
function to add an additional row to an existing dataframe in R. Pass the existing dataframe and the dataframe resulting from the new row as arguments.
The following is the syntax –
rbind(existing_dataframe, data.frame(column_name=column_data))
It returns a new dataframe with the passed row appended to the existing dataframe rows.
Examples
Let’s now look at some examples of using the above syntax in action.
First, we will create our existing dataframe.
# create a dataframe students_df = data.frame( "Name"= c("Ben", "Quinton", "Virat", "Smriti", "Jos"), "Age"= c(23, 27, 24, 21, 26) ) # display the dataframe print(students_df)
Output:
Name Age 1 Ben 23 2 Quinton 27 3 Virat 24 4 Smriti 21 5 Jos 26
The above dataframe contains the name and age information of some students in a university in the columns “Name” and “Age” respectively.
Add a single row to an existing dataframe in R
Let’s say you want to add one more row to the above dataframe—for example, a row with information on a student with the name “Steve” and age 27.
Here, we will use the rbind()
function add an additional row to the dataframe created above.
# add a row to students_df students_df = rbind(students_df, data.frame("Name"="Steve", "Age"=27)) # display the dataframe print(students_df)
Output:
Name Age 1 Ben 23 2 Quinton 27 3 Virat 24 4 Smriti 21 5 Jos 26 6 Steve 27
You can see that the dataframe students_df
now has an additional row with information on the student, “Steve”.
Append multiple rows to an existing dataframe
You can similarly use the rbind()
function to append more than one row to an existing dataframe. For example, let’s add rows for students “Umran” aged 18 and “Bumrah” aged 21 to our above dataframe.
# add multile rows to students_df students_df = rbind(students_df, data.frame("Name"=c("Umran", "Bumrah"), "Age"=c(18, 21))) # display the dataframe print(students_df)
Output:
Name Age 1 Ben 23 2 Quinton 27 3 Virat 24 4 Smriti 21 5 Jos 26 6 Steve 27 7 Umran 18 8 Bumrah 21
You can see that the resulting dataframe has two new rows. Essentially, the rbind()
function is appending a dataframe resulting from new rows to our existing dataframe.
You might also be interested in –
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.