move_columns() moves one or more columns in a data frame to another position.

move_columns(data, ..., .before, .after)

Arguments

data

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.

.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 before the column indicated by .before.

.after

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.

Value

data, with resorted columns.

Note

If neither .before nor .after are specified, the column is moved to the end of the data frame by default.

Examples

data(iris) iris %>% move_columns(Sepal.Width, .after = "Species") %>% 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
iris %>% move_columns(Sepal.Width, .before = Sepal.Length) %>% head()
#> Sepal.Width Sepal.Length Petal.Length Petal.Width Species #> 1 3.5 5.1 1.4 0.2 setosa #> 2 3.0 4.9 1.4 0.2 setosa #> 3 3.2 4.7 1.3 0.2 setosa #> 4 3.1 4.6 1.5 0.2 setosa #> 5 3.6 5.0 1.4 0.2 setosa #> 6 3.9 5.4 1.7 0.4 setosa
iris %>% move_columns(Species, .before = 1) %>% head()
#> Species Sepal.Length Sepal.Width Petal.Length Petal.Width #> 1 setosa 5.1 3.5 1.4 0.2 #> 2 setosa 4.9 3.0 1.4 0.2 #> 3 setosa 4.7 3.2 1.3 0.2 #> 4 setosa 4.6 3.1 1.5 0.2 #> 5 setosa 5.0 3.6 1.4 0.2 #> 6 setosa 5.4 3.9 1.7 0.4
iris %>% move_columns("Species", "Petal.Length", .after = 1) %>% head()
#> Sepal.Length Species Petal.Length Sepal.Width Petal.Width #> 1 5.1 setosa 1.4 3.5 0.2 #> 2 4.9 setosa 1.4 3.0 0.2 #> 3 4.7 setosa 1.3 3.2 0.2 #> 4 4.6 setosa 1.5 3.1 0.2 #> 5 5.0 setosa 1.4 3.6 0.2 #> 6 5.4 setosa 1.7 3.9 0.4
library(dplyr) iris %>% move_columns(contains("Width"), .after = "Species") %>% head()
#> Sepal.Length Petal.Length Species Sepal.Width Petal.Width #> 1 5.1 1.4 setosa 3.5 0.2 #> 2 4.9 1.4 setosa 3.0 0.2 #> 3 4.7 1.3 setosa 3.2 0.2 #> 4 4.6 1.5 setosa 3.1 0.2 #> 5 5.0 1.4 setosa 3.6 0.2 #> 6 5.4 1.7 setosa 3.9 0.4