Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reorder data.table columns (without copying)

Tags:

r

data.table

People also ask

How do you reorder columns in a data table?

ColReorder adds the ability for the end user to be able to reorder columns in a DataTable through a click and drag operation. This can be useful when presenting data in a table, letting the user move columns that they wish to compare next to each other for easier comparison.

How do I reorder columns in DataTable in R?

To reorder data. table columns, the idiomatic way is to use setcolorder(x, neworder) , instead of doing x <- x[, neworder, with=FALSE] . This is because the latter makes an entire copy of the data.

How do I order a data table in R?

To sort a data frame in R, use the order( ) function. By default, sorting is ASCENDING. Prepend the sorting variable by a minus sign to indicate DESCENDING order.

How do I reorder columns in DAX?

RE: How to rearrange calculated columns in Power BI So if you adjust the order in the dax, copy the entire dax for the table, delete the table, create a new table and paste in the dax, it will generate the columns in the order it shows up in the dax.


Use setcolorder():

library(data.table)
x <- data.table(a = 1:3, b = 3:1, c = runif(3))
x
#      a b         c
# [1,] 1 3 0.2880365
# [2,] 2 2 0.7785115
# [3,] 3 1 0.3297416
setcolorder(x, c("c", "b", "a"))
x
#              c b a
# [1,] 0.2880365 3 1
# [2,] 0.7785115 2 2
# [3,] 0.3297416 1 3

From ?setcolorder:

In data.table parlance, all set* functions change their input by reference. That is, no copy is made at all, other than temporary working memory, which is as large as one column.

so should be pretty efficient. See ?setcolorder for details.


One may find it easier to use the above solution, but instead sort by column number. For example: library(data.table)

    > x <- data.table(a = 1:3, b = 3:1, c = runif(3))
    > x
         a b         c
    [1,] 1 3 0.2880365
    [2,] 2 2 0.7785115
    [3,] 3 1 0.3297416
    > setcolorder(x, c(3,2,1))
    > x
         c         b a
    [1,] 0.2880365 3 1
    [2,] 0.7785115 2 2
    [3,] 0.3297416 1 3