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)

# This keeps just dose, which has the same effect for this data set
ToothGrowth %>%
  select(dose)

To remove a column using base R, you can simply assign NULL to that column.

ToothGrowth$len <- NULL

15.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.