Adrian
Adrian

Reputation: 9793

R: rearranging vectors based on rank

> dput(dat)
structure(list(MEMORY1 = c(1, 1, 1, 1), MEMORY2 = c(2, 2, 2, 
2), MEMORY3 = c(3, 3, 3, 3), MEMORY4 = c(4, 4, 4, 4), MEMORY5 = c(5, 
5, 5, 8), MEMORY6 = c(6, 6, 8, 5), MEMORY7 = c(7, 8, 6, 6), MEMORY8 = c(8, 
7, 7, 7)), .Names = c("MEMORY1", "MEMORY2", "MEMORY3", "MEMORY4", 
"MEMORY5", "MEMORY6", "MEMORY7", "MEMORY8"), row.names = c(NA, 
4L), class = "data.frame")
> dat
  MEMORY1 MEMORY2 MEMORY3 MEMORY4 MEMORY5 MEMORY6 MEMORY7 MEMORY8
1       1       2       3       4       5       6       7       8
2       1       2       3       4       5       6       8       7
3       1       2       3       4       5       8       6       7
4       1       2       3       4       8       5       6       7

Suppose I have the above data.frame, and each entry is the rank of the MEMORY item. So for the second row, MEMORY1 had rank 1, MEMORY2 has rank 2, ... MEMORY8 has rank 7, etc.

I want to reorder each row of the data.frame based on the rankings of the MEMORY items.

Row 1 would simply stay the same 1 2 3 4 5 6 7 8

Row 2 should be 1 2 3 4 5 6 8 7 because MEMORY8 is ranked before MEMORY7

Row 3 should be 1 2 3 4 5 7 8 6

Row 4 should be 1 2 3 4 6 7 8 5

How can I write code so that once I pass in dat the output would look something like

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    2    3    4    5    6    7    8
[2,]    1    2    3    4    5    6    8    7
[3,]    1    2    3    4    5    7    8    6
[4,]    1    2    3    4    6    7    8    5

Upvotes: 0

Views: 35

Answers (1)

Pierre L
Pierre L

Reputation: 28441

t(apply(dat, 1, order))
  [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
1    1    2    3    4    5    6    7    8
2    1    2    3    4    5    6    8    7
3    1    2    3    4    5    7    8    6
4    1    2    3    4    6    7    8    5

Upvotes: 3

Related Questions