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:
relocate()
to locate columns relative to each other. See Relative Relocating.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()
.‘_id’
to be the end of the data frame, we set the .after
argument of relocate()
to .after = last_col()
. See Relative Relocating.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.HeExtension: 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:
relocate()
to locate columns relative to each other. See Relative Relocating.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()
.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.