Drop column in R using Dplyr – drop variables

Drop column in R using Dplyr: Drop column in R can be done by using minus before the select function.  Dplyr package in R is provided with select() function which is used to select or drop the columns based on conditions.

We will be using mtcars data to depict, dropping of the variable.

 

Drop by column names in Dplyr:

select() function along with minus which is used to drop the columns by name

library(dplyr)
mydata <- mtcars

# Drop the columns of the dataframe
select (mydata,-c(mpg,cyl,wt))

the above code drops mpg, cyl and wt columns

Drop variables (columns) in R using Dplyr 1

 

Drop 3rd, 4th and 5th columns of the dataframe:

library(dplyr)
mydata <- mtcars

# Drop 3rd,4th and 5th columns of the dataframe
select(mydata,-c(3,4,5))

the above code drops 3rd, 4th and 5th column

Drop variables (columns) in R using Dplyr 2

 

starts_with() function:

Drop the column name which starts with mpg

library(dplyr)
mydata <- mtcars

# Drop column names of the dataframe which starts with
select(mydata,-starts_with("mpg"))

Drop variables (columns) in R using Dplyr 3

 

ends_with() function:

Drop the column name which ends with cyl

library(dplyr)
mydata <- mtcars

# Drop column names of the dataframe which ends with
select(mydata,-ends_with("cyl"))

Drop variables (columns) in R using Dplyr 4

 

contains() function:

Drop the column name which contains “s”

library(dplyr)
mydata <- mtcars

# drop the column names of the dataframe which contains
select(mydata,-contains("s"))

Drop variables (columns) in R using Dplyr 5

 

matches() function:

Drop the column name which matches with “di”

library(dplyr)
mydata <- mtcars

# Drop the columns names of the dataframe which matches
select(mydata,-matches("di"))

Drop variables (columns) in R using Dplyr 6

 

Drop variables (columns) in R using Dplyr prev                                                                                                                Drop variables (columns) in R using Dplyr next