Joyce Z
Joyce Z

Reputation: 31

How to order numeric values in a designed order in R?

My question is: Given the target table(on the right), how can I order rows of the original table(on the left) to get exactly the target table with R? Thank you in advance. enter image description here

Original table:

A   B
1   1
1   2
5   12
2   6
5   14
3   6
3   7
5   13
6   2
3   10
5   11
2   5
6   14
2   7
5   15
6   1
3   8
6   3
2   4
1   3
2   10
4   11
2   8
1   4
1   5
2   9
4   12
4   13
3   9
6   15

Target table:

A   B
1   1
1   2
1   3
1   4
1   5
3   6
3   7
3   8
3   9
3   10
5   11
5   12
5   13
5   14
5   15
6   1
6   2
6   3
2   4
2   5
2   6
2   7
2   8
2   9
2   10
4   11
4   12
4   13
6   14
6   15

Upvotes: 0

Views: 59

Answers (1)

thelatemail
thelatemail

Reputation: 93843

This can be accomplished by ordering by an odd/even flag, and dat$B:

dat[order(-(dat$A %% 2), dat$B),]
##   A  B
##1  1  1
##2  1  2
##20 1  3
##24 1  4
##25 1  5
##6  3  6
##7  3  7
##17 3  8
##29 3  9
##10 3 10
##11 5 11
##3  5 12
##8  5 13
##5  5 14
##15 5 15
##16 6  1
##9  6  2
##18 6  3
##19 2  4
##12 2  5
##4  2  6
##14 2  7
##23 2  8
##26 2  9
##21 2 10
##22 4 11
##27 4 12
##28 4 13
##13 6 14
##30 6 15

If it's not an odd/even split then you can manually set the 1/3/5, and 2/4/6 groups:

dat[order(`levels<-`(factor(dat$A), list('1'=c(1,3,5), '2'=c(6,2,4))), dat$B),]

This collapsed version of the code with levels<- called directly as a function is a bit hard to read, but it is equivalent to:

grpord <- factor(dat$A)
levels(grpord) <- list('1'=c(1,3,5), '2'=c(6,2,4))
dat[order(grpord, dat$B),]

...where "1" is assigned to the groups 1, 3 and 5, and "2" to the groups 6, 2 and 4.

Upvotes: 2

Related Questions