1. The relocate verb
We've learned about the select, rename, and mutate verbs for transforming data, but now we'll learn a fourth one: relocate().
2. Relocate
The relocate verb is used to change column positions using a quick and efficient syntax.
3. counties dataset
Let's continue working with the counties dataset, and use the relocate verb to move the region column to before the state column.
4. Relocating to .before
We begin by piping the counties data into the relocate verb, and specify the column we wish to move as the first argument.
To indicate that we want to move this column before the state column, we pass the state column to the dot-before argument.
Now we can see that that region appears before state in the tibble.
5. Relocating to .after
relocate also has a dot-after argument for specifying that a column should be moved to after another column. Here, we move the state column to after the region column.
6. relocate() + select helpers
We can also combine relocate with the select helpers we saw earlier. Here, we tell the function that we want to move the census_id column to after the final column in the dataset, in effect, moving it to the end.
7. select() vs. relocate()?
You may be wondering why relocate is needed when we can also move columns with select.
The select verb keeps only the columns specified, so it's a good choice if we're subsetting some columns and want to move them at the same time. For example, if we select three columns from counties and want them in a specific order.
The relocate verb keeps all of the columns in the dataset, and because of it's efficient syntax that doesn't require us to list every column we want to keep, it's the best choice when we're only moving columns. For example, if we want the region column before the state column.
8. Let's practice!
You'll get practice of deciding which verbs to use in the following exercises.