Adding New Data Frame Row at Certain Index in R (Example Code)

In this R programming tutorial you’ll learn how to append new rows at a specific position of a data frame.

Creation of Example Data

data(iris)                                               # Iris data set as example data
head(iris)
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          5.1         3.5          1.4         0.2  setosa
# 2          4.9         3.0          1.4         0.2  setosa
# 3          4.7         3.2          1.3         0.2  setosa
# 4          4.6         3.1          1.5         0.2  setosa
# 5          5.0         3.6          1.4         0.2  setosa
# 6          5.4         3.9          1.7         0.4  setosa
my_row <- data.frame(1111, 2222, 3333, 4444, "YAAAAAY")  # Creating new row
colnames(my_row) <- colnames(iris)                       # Equalizing column names
my_row                                                   # Have a look at new row
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1         1111        2222         3333        4444 YAAAAAY

Example: Using rbind() Function to Add Row at Specific Data Frame Position

iris_new <- rbind(iris[1:4, ], my_row, iris[- (1:4), ])  # Adding row
head(iris_new)                                           # Have a look at new data frame
#     Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1            5.1         3.5          1.4         0.2  setosa
# 2            4.9         3.0          1.4         0.2  setosa
# 3            4.7         3.2          1.3         0.2  setosa
# 4            4.6         3.1          1.5         0.2  setosa
# 5         1111.0      2222.0       3333.0      4444.0 YAAAAAY
# 510          5.0         3.6          1.4         0.2  setosa

Further Resources & Related Tutorials

Have a look at the following list of R programming tutorials. They illustrate topics such as indices, extracting data, vectors, and groups.

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top