0

I have a matrix "acc" arranged by years as rows.

       J     F     M   
1989 438.1 364.9 400.9  
1990 359.3 397.9 272.0  
1991 295.3 309.8 297.8 

If I use apply for sorting the columns R cannot hold the rownames as a matrix, so I need to arrange them them one by one for keeping them like this:

         J                 F                 M
1991   295.3      1991   309.8      1990   272.0
1990   359.3      1989   364.9      1991   297.8
1989   438.1      1990   397.9      1989   400.9

I have to perform a sort function by column but by keeping their rownames, so I am doing many arrays like this:

J<-sort(acc[,1])
F<-sort(acc[,2])
M<-sort(acc[,3])

Is there a way to perform the same operation with a loop and keeping the rownames?

Thank you

1 Answers1

1

To do what you want you can save the rownames first, sort by columns and then reassign the rownames.

First a test dataset.

acc <- matrix(30:1, nrow = 10)
rownames(acc) <- paste("Year", 1:10, sep = ".")

Now the code.

rn <- rownames(acc)
acc <- apply(acc, 2, sort)
rownames(acc) <- rn

acc
#        [,1] [,2] [,3]
#Year.1    21   11    1
#Year.2    22   12    2
#Year.3    23   13    3
#Year.4    24   14    4
#Year.5    25   15    5
#Year.6    26   16    6
#Year.7    27   17    7
#Year.8    28   18    8
#Year.9    29   19    9
#Year.10   30   20   10
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66