Mixalis Mixalis - 23 days ago 10
R Question

Reorder all the columns in a data table based on Other files rows

So I have a sorted data.table that looks like this:

POS ID
11 id1
12 id2
13 id3
21 id4
22 id5
...


And another
data.table
file that looks like this:

SOURCE id1 id4 id3 id5 ...
source1 1 321 65 57
source2 5 6 65 4
source3 32 3 0 5


So in other words, the second data.table has the ids from the first data.table as collumn names.

I 'm a newbie in R, and I would like to sort all the columns of the second data.table based on the order of the first without harming the first column.

so my
result
data.table should look like this:

SOURCE id1 id2 id3 id4 id5 ...
source1 1 312 65 321 57
source2 5 54 65 6 4
source3 32 6 0 3 5


I'm struggling with match. but i'm getting errors. :/

Answer

a base/dplyr approach:

new_order <- sapply(df1$ID, grep, colnames(df2)) %>% unlist()

select(df2, SOURCE, new_order)

   SOURCE id1 id3 id4 id5
1 source1   1  65 321  57
2 source2   5  65   6   4
3 source3  32   0   3   5
Comments