LeGeniusII
LeGeniusII

Reputation: 960

data.table reorder columns by index

I have:

> aDT <- data.table(col5 = 5, col1 = 1, col2 = 2, col4 = 4, col3 = 3)
> aDT
   col5 col1 col2 col4 col3
1:    5    1    2    4    3

as well as:

index1 <- c(5,1,2)
index2 <- c(4,3)

I need:

> aDT <- data.table(col1 = 1, col2 = 2, col3 = 3, col4 = 4, col5 = 5)
> aDT
   col1 col2 col3 col4 col5
1:    1    2    3    4    5

Have tried:

> setcolorder(aDT,c(index1,index2))
> aDT
   col3 col5 col1 col4 col2
1:    3    5    1    4    2

As you can see, it's not working. Can anyone help?

Upvotes: 3

Views: 1404

Answers (4)

MKR
MKR

Reputation: 20095

It's working per expectation. Look at current column order:

> aDT <- data.table(col5 = 5, col1 = 1, col2 = 2, col4 = 4, col3 = 3)
> aDT
   col5 col1 col2 col4 col3
1:    5    1    2    4    3

Now, > setcolorder(aDT,c(index1,index2)) is suggesting to change order as 5,1,2,4,3. Means moving current column from 5 to 1, from 1 to 2, 2 to 3 and so on.

I think what you want can be achieved in simple lines:

> setcolorder(aDT,sort(names(aDT))
> aDT
   col1 col2 col3 col4 col5
1:    1    2    3    4    5

Upvotes: 2

LeGeniusII
LeGeniusII

Reputation: 960

Should be using:

setcolorder(aDT,order(c(index1,index2)))

Thanks for the tips.

Upvotes: 3

akrun
akrun

Reputation: 887751

We can use match

setcolorder(aDT, match(seq_along(aDT), c(index1, index2)))
aDT
#   col1 col2 col3 col4 col5
#1:    1    2    3    4    5

Upvotes: 5

Linus
Linus

Reputation: 725

It does exactly what you want it to do. You provide column indices and not the colnames. It takes the 5th column first which is called 'col3' then it takes the first one which is 'col5' and so on. You can use the colnames by providing the colnames in the correct order you want.

Upvotes: 0

Related Questions