How to delete rows from a data frame in R


  R Interview Questions

Deleting rows is typically done using sub-setting.

For example, you want to delete all rows where species = “setosa” or “virginica”

> 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

Use sub-setting and assign to a new variable

> iris_versicolor = iris_small[iris_small$species %in% c("setosa","Virginica"),]
> iris_versicolor
   Sepal.Length Sepal.Width Petal.Length petal.Width   species
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

Leave a Reply

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