Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R change order of column values in a data.table according to a permutation

I have a data.table with a class column and a number of value columns, e.g.

     class  v1  v2  v3
1:       1  10   3   8
2:       2   2  24   7
3:       1  70   3   9

Now, for a subset of data.table (say class=1), I need to change the order of values in each row according to a permutation that I have. For instance, if the permutation is

3   1   2

The result should look like

     class  v1  v2  v3
1:       1   8  10   3
2:       2   2  24   7
3:       1   9  70   3

What's the best way to achieve this using data.table?

I can alternatively convert my data to matrix, if that's more efficient. Thanks!

like image 313
amir Avatar asked Dec 30 '25 22:12

amir


1 Answers

Something like this should work

 DT <- data.table(class = sample(1:3, 10, TRUE), v1 =sample(10), v2 = sample(10), v3 = sample(10))
 DT
    class v1 v2 v3
 1:     1  4  6  6
 2:     1  7  1  5
 3:     1  5  5 10
 4:     1  3  8  7
 5:     3  8  4  3
 6:     3  9  7  9
 7:     2  1  3  8
 8:     2 10 10  2
 9:     1  2  2  4
10:     2  6  9  1

# the neworder column contains the new permutations
swapcols <- data.table(class = 1:3, neworder = list(c(1,2,3), c(3,1,2),c(1,3,2)))

setkey(DT, class)
setkey(swapcols, class)

DT[swapcols, setNames(list(v1,v2,v3)[unlist(neworder)], c('v1','v2','v3'))]

    class v1 v2 v3
 1:     1  4  6  6
 2:     1  7  1  5
 3:     1  5  5 10
 4:     1  3  8  7
 5:     1  2  2  4
 6:     2  8  1  3
 7:     2  2 10 10
 8:     2  1  6  9
 9:     3  8  3  4
10:     3  9  9  7

It would probably be even more efficient to do something like

  DT[swapcols, setcolorder(.SD, unlist(neworder))]

or

  new <- DT[swapcols, list(v1,v2,v3)[unlist(neworder)]]
  setnames(new, names(new), c('class', c('v1','v2','v3'))

You could also use :=. something like

 DT[J(1), `:=`(v1= v2,v2=v3,v3=v1)]

You could try some way of automating this within a function, but it would be a mess of eval / parse and do.call


From Matthew (tested in v1.8.3) :

DT = data.table(class=c(1,2,1),v1=c(10,2,70),v2=c(3,24,3),v3=c(8,7,9))
DT
   class v1 v2 v3
1:     1 10  3  8
2:     2  2 24  7
3:     1 70  3  9

perm = c(3,1,2)
DT[class==1, names(DT)[-1L] := .SD, .SDcols = perm+1L]]
DT
   class v1 v2 v3
1:     1  8 10  3
2:     2  2 24  7
3:     1  9 70  3
like image 181
mnel Avatar answered Jan 01 '26 13:01

mnel