Select() by indices

select(my_data_frame, column_one, column_two, ...)
select(my_data_frame, new_column_name = current_column, ...)
select(my_data_frame, column_start:column_end)
select(my_data_frame, index_one, index_two, ...)
select(my_data_frame, index_start:index_end)
View Interactive Version

The select() function can be used with column indices as well. Instead of using names we need to specify the columns we want to select by their indices. Compared to other programming languages the indexing in R starts with one instead of zero. To select the first, fourth and fifth column from the pres_results dataset we can write

Input
select(pres_results, 1,4,5)
Output
# A tibble: 561 x 3
   year   dem   rep
  <dbl> <dbl> <dbl>
1  1976 0.357 0.579
2  1976 0.557 0.426
3  1976 0.650 0.349
# … with 558 more rows

Similarly to defining ranges of columns using their names, we can define ranges (or vectors) of index values instead:

Input
select(pres_results, 1:3)
Output
# A tibble: 561 x 3
   year state total_votes
  <dbl> <chr>       <dbl>
1  1976 AK         123574
2  1976 AL        1182850
3  1976 AR         767535
# … with 558 more rows
Select columns from a data frame