6.5 select()

Function: Select only the columns (variables) that you want to see. Gets rid of all other columns. You can to refer to the columns by the column position (first column) or by name. The order in which you list the column names/positions is the order that the columns will be displayed.

In the diamonds dataset, only retain cut and color:

diamonds %>% select(cut, color)

Only retain the first five columns:

diamonds %>% select(1:5)

# or

diamonds %>% select(1,2,3,4,5)

Retain all of the columns except for cut:

diamonds %>% select(-cut)

Retain all of the columns except for cut and color:

diamonds %>% select(-cut, -color)

Retain all of the columns except for the first five columns:

diamonds %>% select (-1,-2,-3,-4,-5)
# or
diamonds %>% select(-(1:5))

You can also retain all of the columns, but rearrange some of the columns to appear at the beginning—this moves the x,y,z variables to the first 3 columns:

diamonds %>% select(x,y,z, everything())