Use `relocate()` to change column positions, using the same syntax as `select()`. Check similar function as `relocate()` in dplyr.
relocate(.data, ..., how = "first", where = NULL)
.data | A data.table |
---|---|
... | Columns to move |
how | The mode of movement, including "first","last","after","before". Default uses "first". |
where | Destination of columns selected by |
A data.table with rearranged columns.
Once you relocate the columns, the order changes forever.
#> a b c d e f #> <num> <num> <num> <char> <char> <char> #> 1: 1 1 1 a a adf %>% relocate(f)#> f a b c d e #> <char> <num> <num> <num> <char> <char> #> 1: a 1 1 1 a adf %>% relocate(a,how = "last")#> f b c d e a #> <char> <num> <num> <char> <char> <num> #> 1: a 1 1 a a 1df %>% relocate(is.character)#> f d e b c a #> <char> <char> <char> <num> <num> <num> #> 1: a a a 1 1 1df %>% relocate(is.numeric, how = "last")#> f d e b c a #> <char> <char> <char> <num> <num> <num> #> 1: a a a 1 1 1df %>% relocate("[aeiou]")#> e a f d b c #> <char> <num> <char> <char> <num> <num> #> 1: a 1 a a 1 1df %>% relocate(a, how = "after",where = f)#> e f a d b c #> <char> <char> <num> <char> <num> <num> #> 1: a a 1 a 1 1df %>% relocate(f, how = "before",where = a)#> e f a d b c #> <char> <char> <num> <char> <num> <num> #> 1: a a 1 a 1 1df %>% relocate(f, how = "before",where = c)#> e a d b f c #> <char> <num> <char> <num> <char> <num> #> 1: a 1 a 1 a 1df %>% relocate(f, how = "after",where = c)#> e a d b c f #> <char> <num> <char> <num> <num> <char> #> 1: a 1 a 1 1 adf2 <- data.table(a = 1, b = "a", c = 1, d = "a") df2 %>% relocate(is.numeric, how = "after", where = is.character)#> b d a c #> <char> <char> <num> <num> #> 1: a a 1 1df2 %>% relocate(is.numeric, how="before", where = is.character)#> a c b d #> <num> <num> <char> <char> #> 1: 1 1 a a