How to delete columns from a data frame in R

How to delete columns from a data frame in R


  R Interview Questions

Click here for more R Interview Questions

1 – Setting the column to NULL

Say you want to remove the species column.

> 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

Set the column to NULL

> iris_small$species = NULL
> 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

2 – sub-setting

> iris_no_species = iris_small[,-5]
> iris_no_species
    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

Leave a Reply

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

%d bloggers like this: