How can you add rows to a data frame in R


  R Interview Questions

1 – RBIND ()

> iris_small
    Sepal.Length Sepal.Width Petal.Length Petal.Width
1            5.1         3.5          1.4         0.2
2            4.9         3.0          1.4         0.2
3            4.7         3.2          1.3         0.2
51           7.0         3.2          4.7         1.4
52           6.4         3.2          4.5         1.5
53           6.9         3.1          4.9         1.5
101          6.3         3.3          6.0         2.5
102          5.8         2.7          5.1         1.9
103          7.1         3.0          5.9         2.1

Say we have a new observation we want to add to the data set above.

> new_obs = c(8.1, 3.1,6.1,2.5)

use the RBIND function

> rbind(iris_small,new_obs)
    Sepal.Length Sepal.Width Petal.Length Petal.Width
1            5.1         3.5          1.4         0.2
2            4.9         3.0          1.4         0.2
3            4.7         3.2          1.3         0.2
51           7.0         3.2          4.7         1.4
52           6.4         3.2          4.5         1.5
53           6.9         3.1          4.9         1.5
101          6.3         3.3          6.0         2.5
102          5.8         2.7          5.1         1.9
103          7.1         3.0          5.9         2.1
10           8.1         3.1          6.1         2.5

2 – RBIND() to more than one observation

In fact, RBIND () can be used to add more than just 1 observation – say add an entire data frame to another.

Let’s create a new data frame as a subset of iris

> new_obs = iris_small[c(1,3,9),]
> new_obs
    Sepal.Length Sepal.Width Petal.Length Petal.Width
1            5.1         3.5          1.4         0.2
3            4.7         3.2          1.3         0.2
103          7.1         3.0          5.9         2.1

new_obs is an entire new data frame with 3 rows. use RBIND() to add this new data frame to the iris data frame.

> rbind(iris_small,new_obs)
     Sepal.Length Sepal.Width Petal.Length Petal.Width
1             5.1         3.5          1.4         0.2
2             4.9         3.0          1.4         0.2
3             4.7         3.2          1.3         0.2
51            7.0         3.2          4.7         1.4
52            6.4         3.2          4.5         1.5
53            6.9         3.1          4.9         1.5
101           6.3         3.3          6.0         2.5
102           5.8         2.7          5.1         1.9
103           7.1         3.0          5.9         2.1
11            5.1         3.5          1.4         0.2
31            4.7         3.2          1.3         0.2
1031          7.1         3.0          5.9         2.1

Caution – Ensure that the column names are an exact match including case.

> rbind(iris_small,new_obs)
Error in match.names(clabs, names(xi)) : 
  names do not match previous names

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.