Move columns within a data frame
relocate.RdMove one or more columns within an existing data frame.
Arguments
- data
A data frame.
- x
A character vector of column names, integer vector of positions, or logical vector of positions that will be moved.
- before, after
An integer for the column index or string for the column name of where to move the columns. Defaults to after last column. Only specify one of these arguments.
References
Hadley Wickham, Romain François, Lionel Henry and Kirill Müller (2020). dplyr: A Grammar of Data Manipulation. R package version 1.0.2. https://CRAN.R-project.org/package=dplyr
Examples
#----------------------------------------------------------------------------
# relocate() examples
#----------------------------------------------------------------------------
library(bkdat)
df <- data.frame(a = 1, b = 1, c = 1, d = "a", e = "a", f = "a")
relocate(data = df, x = "b", before = "e")
#> a c d b e f
#> 1 1 1 a 1 a a
relocate(df, "a", after = "c")
#> b c a d e f
#> 1 1 1 1 a a a
relocate(df, "f", before = "b")
#> a f b c d e
#> 1 1 a 1 1 a a
relocate(df, "a")
#> b c d e f a
#> 1 1 1 a a a 1
# Can also select variables based on their type
relocate(df, x = unlist(lapply(df, is.character)))
#> a b c d e f
#> 1 1 1 1 a a a
relocate(df, x = unlist(lapply(df, is.numeric)))
#> d e f a b c
#> 1 a a a 1 1 1
relocate(df, x = unlist(lapply(df, is.character)), after = "b")
#> a b d e f c
#> 1 1 1 a a a 1
relocate(df, x = unlist(lapply(df, is.numeric)), before = "e")
#> d a b c e f
#> 1 a 1 1 1 a a