Drop Multiple Columns from Data Frame Using dplyr Package in R (Example)


In this R tutorial you’ll learn how to remove several variables of a data frame based on functions of the dplyr package.

The article is structured as follows:

Let’s start right away.


Creation of Example Data

As a first step, we’ll have to define some data that we can use in the following examples:

data <- data.frame(x1 = 1:5,    # Create data
                   x2 = letters[1:5],
                   x3 = 5,
                   x4 = c(3, 1, 6, 3, 7))
data                            # Print data
#   x1 x2 x3 x4
# 1  1  a  5  3
# 2  2  b  5  1
# 3  3  c  5  6
# 4  4  d  5  3
# 5  5  e  5  7

The previous RStudio console output shows the structure of the example data – It contains of five rows and four columns.


Example: Remove Several Variables Using select & one_of Functions

In this Example, I’ll explain how to extract multiple columns from a data matrix using the dplyr package.

We first need to install and load the dplyr package:

install.packages("dplyr")       # Install dplyr package
library("dplyr")                # Load dplyr

Now, we have to define the column names of the variables we want to drop:

col_remove <- c("x1", "x3")     # Define columns that should be dropped

Finally, we can use the select and one_of functions of the dplyr package to delete the preliminarily defined variables:

data_new <- data %>%            # Apply select & one_of functions
  select(- one_of(col_remove))
data_new                        # Print updated data
#   x2 x4
# 1  a  3
# 2  b  1
# 3  c  6
# 4  d  3
# 5  e  7

Have a look at the output of the RStudio console: Only the variables x2 and x4 were kept in our new data matrix.


Video & Further Resources

Do you need further explanations on the content of this article? Then you might want to watch the following video tutorial of my YouTube channel. I illustrate the R syntax of this tutorial in the video:



Furthermore, you may want to read the related tutorials on this website. I have published numerous articles already.


In summary: You learned in this article how to delete columns using dplyr in R. If you have any further questions, don’t hesitate to let me know in the comments. Furthermore, please subscribe to my email newsletter to receive updates on the newest tutorials.


Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.