How can you add columns or rows to a data frame in R

How can you add columns or rows to a data frame in R


  R Interview Questions

1 – CBIND () to add columns

> 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 want to add the species column.

> species = c("Setosa","Setosa","Setosa","Virginica","Virginica","Virginica","Versicolor","Versicolor","Versicolor")

use “Column” bind – CBIND() function to add the species vector as a new column.

> iris_small_species = cbind(iris_small,species)
> iris_small_species
    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
51           7.0         3.2          4.7         1.4  Virginica
52           6.4         3.2          4.5         1.5  Virginica
53           6.9         3.1          4.9         1.5  Virginica
101          6.3         3.3          6.0         2.5 Versicolor
102          5.8         2.7          5.1         1.9 Versicolor
103          7.1         3.0          5.9         2.1 Versicolor

CBIND() is good if you want to add data programmatically – say in a loop. If you want to do it ad-hoc, you can dynamically do it using the

2- $ method.

> iris_small$species = species
> iris_small
    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
51           7.0         3.2          4.7         1.4  Virginica
52           6.4         3.2          4.5         1.5  Virginica
53           6.9         3.1          4.9         1.5  Virginica
101          6.3         3.3          6.0         2.5 Versicolor
102          5.8         2.7          5.1         1.9 Versicolor
103          7.1         3.0          5.9         2.1 Versicolor

Leave a Reply

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

%d bloggers like this: