move_columns()
moves one or more columns in a data frame
to another position.
move_columns(data, ..., .before, .after)
A data frame.
Unquoted names or character vector with names of variables that
should be move to another position. You may also use functions like
:
or tidyselect's select-helpers.
Optional, column name or numeric index of the position where
col
should be moved to. If not missing, col
is moved to the
position before the column indicated by .before
.
Optional, column name or numeric index of the position where
col
should be moved to. If not missing, col
is moved to the
position after the column indicated by .after
.
data
, with resorted columns.
If neither .before
nor .after
are specified, the
column is moved to the end of the data frame by default. .before
and .after
are evaluated in a non-standard fashion, so you need
quasi-quotation when the value for .before
or .after
is
a vector with the target-column value. See 'Examples'.
if (FALSE) {
data(iris)
iris %>%
move_columns(Sepal.Width, .after = "Species") %>%
head()
iris %>%
move_columns(Sepal.Width, .before = Sepal.Length) %>%
head()
iris %>%
move_columns(Species, .before = 1) %>%
head()
iris %>%
move_columns("Species", "Petal.Length", .after = 1) %>%
head()
library(dplyr)
iris %>%
move_columns(contains("Width"), .after = "Species") %>%
head()}
# using quasi-quotation
target <- "Petal.Width"
# does not work, column is moved to the end
iris %>%
move_columns(Sepal.Width, .after = target) %>%
head()
#> Sepal.Length Petal.Length Petal.Width Species Sepal.Width
#> 1 5.1 1.4 0.2 setosa 3.5
#> 2 4.9 1.4 0.2 setosa 3.0
#> 3 4.7 1.3 0.2 setosa 3.2
#> 4 4.6 1.5 0.2 setosa 3.1
#> 5 5.0 1.4 0.2 setosa 3.6
#> 6 5.4 1.7 0.4 setosa 3.9
# using !! works
iris %>%
move_columns(Sepal.Width, .after = !!target) %>%
head()
#> Sepal.Length Petal.Length Petal.Width Sepal.Width Species
#> 1 5.1 1.4 0.2 3.5 setosa
#> 2 4.9 1.4 0.2 3.0 setosa
#> 3 4.7 1.3 0.2 3.2 setosa
#> 4 4.6 1.5 0.2 3.1 setosa
#> 5 5.0 1.4 0.2 3.6 setosa
#> 6 5.4 1.7 0.4 3.9 setosa