r - Extract values corresponding to top k of any other column -


how in 1 table, values of 'x' corresponding top k values of 'y' , of 'z' ?

> dt <- data.table( x = letters[c(1, 1, 3, 2, 3, 1, 1)],                     y = c(1, 2, 1, 2, 2, 1, 1), z = c(1, 2, 3) ) > dt    x y z 1: 1 1 2: 2 2 3: c 1 3 4: b 2 1 5: c 2 2 6: 1 3 7: 1 1 

can case solved join, or must loop on columns not 'x'?

> requested.output    var x val 1:   y   2 2:   y b   2 3:   y c   2 4:   z c   3 5:   z   3 6:   z   2 

no need loop or join, can convert long format according x column, sort value in decreasing order, , select first 3 rows according each variable.

melt(dt, id = "x")[order(-value), .sd[1:3], keyby = variable] #    variable x value # 1:        y     2 # 2:        y b     2 # 3:        y c     2 # 4:        z c     3 # 5:        z     3 # 6:        z     2 

Comments