Remove Or Delete A Column Of A Data Frame In R

In this tutorial, we’re going to show how to remove or delete a column of a data frame in R.

1. Preparation

Let’s create a data frame which will be used for all examples in this tutorial:

And let’s see it:

1. Delete A Column Of A Data Frame In R Directly

To remove or delete a column of a data frame, we can set that column to NULL which is a reserved word and represents the null object in R. For example, let’s delete the column “hair” of the above data frame:

And let’s see the data frame content:

We can see that the column “hair” was deleted from the data frame.

Because there are other different ways to select a column of a data frame in R, we can have different ways to remove or delete a column of a data frame in R, for example:

To delete the column “hair” from the original data frame:

Or

We can achieve the same result with the first way. Let’s see the data frame again:

3. Delete A Column Of A Data Frame By Subsetting

Another approach for us to remove or delete a column of a data frame in R is to leveraging the subsetting of a data frame, for example, to delete the column “eye” which is the 4th column of the above data frame:

or

and see the data frame content:

The 4th column was deleted.

Notice that the [, -4] or [-4] mean to drop the 4th column from the data frame “children”(or take all columns but the 4th from the data frame “children”).

4. Delete Multiple Columns Of A Data Frame

4.1. Delete Multiple Columns By Index

In similar to deleting a column of a data frame, to delete multiple columns of a data frame, we simply need to put all desired column into a vector and set them to NULL, for example, to delete the 2nd, 4th columns of the above data frame:

Let’s have a look at the result:

To drop the columns 2, 3, 4 of the data frame:

And the result:

4.2. Delete Multiple Columns By Names

To remove or delete multiple columns of a data frame  by names, we need to provides the list of names when subsetting, for example, to delete the columns “hair” and “eye” of the above data frame:

The result:

Or, alternatively, we make a list of columns need to keep and refer to them by name:

The result is identical to the above example:

5. Conclusion

The tutorial has shown us how to remove or delete a column of a data frame in R by two approaches. The first one is to remove or delete the column directly, and the second one is to through subsetting the data frame.

Below are other related tutorials for your references: