15.4 Deleting a Column from a Data Frame
15.4.1 Problem
You want to delete a column from a data frame. This returns a new data frame, which you’ll typically want save over the original.
15.4.2 Solution
Use select() from dplyr and specify the columns you want to drop by using - (a minus sign).
# Remove the len column
ToothGrowth %>%
select(-len)15.4.3 Discussion
You can list multiple columns that you want to drop at the same time, or conversely specify only the columns that you want to keep. The following two pieces of code are thus equivalent:
# Remove both len and supp from ToothGrowth
ToothGrowth %>%
select(-len, -supp)
#> dose
#> 1 0.5
#> 2 0.5
#> ...<56 more rows>...
#> 59 2.0
#> 60 2.0
# This keeps just dose, which has the same effect for this data set
ToothGrowth %>%
select(dose)
#> dose
#> 1 0.5
#> 2 0.5
#> ...<56 more rows>...
#> 59 2.0
#> 60 2.0To remove a column using base R, you can simply assign NULL to that column.
# Make a copy of ToothGrowth for this example
ToothGrowth2 <- ToothGrowth
ToothGrowth2$len <- NULL15.4.4 See Also
Recipe 15.7 for more on getting a subset of a data frame.
See ?select for more ways to drop and keep columns.