Basic Relocating

We wish to obtain a set of columns of a data frame, that contains some or all columns, sorted in a given order.

This section is organized as follows:

  • By Name: We refer to the columns whose location we wish to change by their name.
  • By Location: We refer to the columns whose location we wish to change by their location (integer) in the original data frame.

By Name

We wish to change the locations of the columns of a data frame by spelling out their names in the desired order.

df_2 = df %>% 
    select(col_3, col_1, col_4, col_2)

Here is how this works:

  • The order of the columns in the output data frame is determined by the order of the column names we provide to select(). See Basic Selecting.
  • Columns that are not mentioned in the call to select() will be dropped. See Relative Relocating for how to relocate certain columns relative to the rest.

By Location

We wish to change the locations of the columns of a data frame by spelling out their numerical positions (in the original data frame) in the desired order.

df_2 = df %>% 
    select(3, 1, 4, 2)

Here is how this works:

  • This works similarly to the By Name scenario above except that the order of the columns in the output data frame is determined by the order of the current column positions we provide to select().
  • As a reminder, positions in R start at 1.
R
I/O