Select variables (columns) in R using Dplyr – select () Function

Select function in R is used to select variables (columns) in R using Dplyr package.  Dplyr package in R is provided with select() function which select the columns based on conditions.

We will be using mtcars data to depict the select() function

select () Function in Dplyr:

library(dplyr)
mydata <- mtcars

# Select columns of the dataframe
select(mydata,mpg,cyl,wt)

The above code selects mpg, cyl and wt column

Select variables (columns) in R using Dplyr Select Function in R dplyr 1

 

Select 3rd and 4th columns of the dataframe:

library(dplyr)
mydata <- mtcars

# Select 3rd and 4th columns of the dataframe
select(mydata,3:4)

the above code selects disp and hp column

Select variables (columns) in R using Dplyr Select Function in R dplyr 2

 

starts_with() function:

Select the column name which starts with mpg

library(dplyr)
mydata <- mtcars

# Select on columns names of the dataframe which starts with
select(mydata,starts_with("mpg"))

Select variables (columns) in R using Dplyr Select Function in R dplyr 4

Select the column names which does not starts with mpg

library(dplyr)
mydata <- mtcars

# deselect on columns names of the dataframe which starts with
select(mydata,-starts_with("mpg"))

Select variables (columns) in R using Dplyr Select Function in R dplyr 6

 

ends_with() function:

Select the column name which ends with cyl

library(dplyr)
mydata <- mtcars

# Select on columns names of the dataframe which ends with
select(mydata,ends_with("cyl"))

Select variables (columns) in R using Dplyr Select Function in R dplyr 5

 

contains() function:

Select the column name which contains “s”

library(dplyr)
mydata <- mtcars

# Select on columns names of the dataframe which contains
select(mydata,contains("s"))

Select variables (columns) in R using Dplyr Select Function in R dplyr 7

matches() function:

Select the column name which matches with “di”

library(dplyr)
mydata <- mtcars

# Select on columns names of the dataframe which matches
select(mydata,matches("di"))

Select variables (columns) in R using Dplyr Select Function in R dplyr 8

 

everything() function:

select everything /all columns of the dataframe

library(dplyr)
mydata <- mtcars

# Select everything
select(mydata,everything())

Select variables (columns) in R using Dplyr Select Function in R dplyr 9

 

Select variables (columns) in R using Dplyr – select () Function prev                                                                                                                Select variables (columns) in R using Dplyr – select () Function