data.table按索引重新排序列

LeG*_*sII 3 r data.table

我有:

> 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
Run Code Online (Sandbox Code Playgroud)

以及:

index1 <- c(5,1,2)
index2 <- c(4,3)
Run Code Online (Sandbox Code Playgroud)

我需要:

> 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
Run Code Online (Sandbox Code Playgroud)

试过:

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

如你所见,它不起作用.有人可以帮忙吗?

akr*_*run 5

我们可以用 match

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