maniA
maniA

Reputation: 1457

How can I sort the rows of a data.table based on arbitrary order?

I want to sort the data.table (dat):

Rating  el  es
A   21.96   0.15
AA  26.25   0.13
AAA 34.07   0.06
B   0.84    0.07
BB  2.24    0.07
BBB 14.63   0.52
CCC 70.48   0.04

By applying

dat[order(dat$Rating)]

I get the same result.

Is it possible to get an arbitrary order based on an arbitrary ordering of column rating?

Something like this:

Rating  el  es
AAA 34,07   0,06
AA  26,25   0,13
A   21,96   0,15
BBB 14,63   0,52
BB  2,24    0,07
B   0,84    0,07
CCC 70,48   0,04

I have tried:

dat[order(dat[,1],levels = c("AAA","AA","A","BBB", "BB", "B", "CCC"))]

but I get the same order in the table as before.

Upvotes: 4

Views: 906

Answers (3)

hkosm
hkosm

Reputation: 1

Since you asked for an arbitrary order, try using appropriate indexing:

 dat[c(3,2,1,6,5,4,7),]
# Rating    el   es
#     AAA 34.07 0.06
#      AA 26.25 0.13
#       A 21.96 0.15
#     BBB 14.63 0.52
#      BB  2.24 0.07
#       B  0.84 0.07
#     CCC 70.48 0.04

Upvotes: 0

markus
markus

Reputation: 26373

Here is an option that uses setorder from data.table which should by really fast. I create a grouping variable first, which is based on @akrun's answer to your previous question.

dat[, grp := substr(Rating, 1, 1)]
setorder(dat, grp, -Rating)[]
#   Rating    el   es grp
#1:    AAA 34.07 0.06   A
#2:     AA 26.25 0.13   A
#3:      A 21.96 0.15   A
#4:    BBB 14.63 0.52   B
#5:     BB  2.24 0.07   B
#6:      B  0.84 0.07   B
#7:    CCC 70.48 0.04   C

data

dat <- data.table::fread(
  "Rating  el  es
  A   21.96   0.15
  AA  26.25   0.13
  AAA 34.07   0.06
  B   0.84    0.07
  BB  2.24    0.07
  BBB 14.63   0.52
  CCC 70.48   0.04"
)

Upvotes: 2

RLave
RLave

Reputation: 8374

You need to change Rating to factor first, then use order:

dat$Rating <- factor(dat$Rating, levels = c("AAA","AA","A","BBB", "BB", "B", "CCC"))

dat[order(dat$Rating), ]
# Rating    el   es
# 3    AAA 34.07 0.06
# 2     AA 26.25 0.13
# 1      A 21.96 0.15
# 6    BBB 14.63 0.52
# 5     BB  2.24 0.07
# 4      B  0.84 0.07
# 7    CCC 70.48 0.04

Data:

tt <- "Rating  el  es
A   21.96   0.15
AA  26.25   0.13
AAA 34.07   0.06
B   0.84    0.07
BB  2.24    0.07
BBB 14.63   0.52
CCC 70.48   0.04"

dat <- read.table(text = tt, header = T)

Upvotes: 4

Related Questions