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)

Arguments

.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 .... Applicable for "after" and "before" mode.

Value

A data.table with rearranged columns.

Details

Once you relocate the columns, the order changes forever.

Examples

df <- data.table(a = 1, b = 1, c = 1, d = "a", e = "a", f = "a")
df
#>        a     b     c      d      e      f
#>    <num> <num> <num> <char> <char> <char>
#> 1:     1     1     1      a      a      a
df %>% relocate(f)
#>         f     a     b     c      d      e
#>    <char> <num> <num> <num> <char> <char>
#> 1:      a     1     1     1      a      a
df %>% relocate(a,how = "last")
#>         f     b     c      d      e     a
#>    <char> <num> <num> <char> <char> <num>
#> 1:      a     1     1      a      a     1

df %>% relocate(is.character)
#>         f      d      e     b     c     a
#>    <char> <char> <char> <num> <num> <num>
#> 1:      a      a      a     1     1     1
df %>% relocate(is.numeric, how = "last")
#>         f      d      e     b     c     a
#>    <char> <char> <char> <num> <num> <num>
#> 1:      a      a      a     1     1     1
df %>% relocate("[aeiou]")
#>         e     a      f      d     b     c
#>    <char> <num> <char> <char> <num> <num>
#> 1:      a     1      a      a     1     1

df %>% relocate(a, how = "after",where = f)
#>         e      f     a      d     b     c
#>    <char> <char> <num> <char> <num> <num>
#> 1:      a      a     1      a     1     1
df %>% relocate(f, how = "before",where = a)
#>         e      f     a      d     b     c
#>    <char> <char> <num> <char> <num> <num>
#> 1:      a      a     1      a     1     1
df %>% relocate(f, how = "before",where = c)
#>         e     a      d     b      f     c
#>    <char> <num> <char> <num> <char> <num>
#> 1:      a     1      a     1      a     1
df %>% relocate(f, how = "after",where = c)
#>         e     a      d     b     c      f
#>    <char> <num> <char> <num> <num> <char>
#> 1:      a     1      a     1     1      a

df2 <- 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     1
df2 %>% relocate(is.numeric,
                    how="before",
                    where = is.character)
#>        a     c      b      d
#>    <num> <num> <char> <char>
#> 1:     1     1      a      a