Implicit Relocating

We do not explicitly specify the columns we wish to relocate by name or position, rather we refer to them implicitly.

In this example, we wish to relocate columns ending with the suffix ‘_id’ to be the end of the data frame.

df_2 = df %>%
  relocate(ends_with('_id'), .after = last_col())

Here is how this works:

  • We use relocate() to locate columns relative to each other. See Relative Relocating.
  • We pass to the first argument of relocate(), the expression ends_with('_id') to select all columns whose name ends with ‘_id’. See Implicit Selection for coverage of common scenarios of implicit column selection, including by name pattern, data type, and criteria satisfied by the column’s data, all of which may be used with relocate().
  • Since we wish to move columns ending with the suffix ‘_id’ to be the end of the data frame, we set the .after argument of relocate() to .after = last_col(). See Relative Relocating.
  • The output data frame df_2 will be a copy of the input data frame df but with columns ending with the suffix ‘_id’ to be the end of the data frame.He

Extension: Relative to Implicitly Selected Group

We wish to relocate a set of implicitly selected columns to be located relative to, i.e. before or after, another set of implicitly selected columns.

In this example, we wish to have character columns come before numeric columns (which is oftentimes a good practice when working with actual datasets).

df_2 = df %>%
  relocate(where(is.character), .before = where(is.numeric))

Here is how this works:

  • We use relocate() to locate columns relative to each other. See Relative Relocating.
  • In this case, our aim is to have character columns come before numerical columns, therefore we pass where(is.character) to the first argument of relocate() to select all character columns and where(is.numeric) to the second argument of relocate() to select all numeric columns. See Implicit Selection for coverage of common scenarios of implicit column selection, including by name pattern, data type, and criteria satisfied by the column’s data, all of which may be used with relocate().
  • Note that columns of any other data type will show after numeric columns.
  • The output data frame df_2 will be a copy of the input data frame df but with character columns appearing before numeric columns and any other columns appearing after.
R
I/O