Tuesday, April 29, 2014

Quickly reverse a matrix in R

If you have a matrix in R, and want to reverse it do the following brilliant step:
matrix <- matrix[nrow(matrix):1, ]
This will list rows from the matrix in reverse order from nrow(matrix) to 1

e.g.

   Number Year per100k
1     419 2013  37.394
2     342 2012  32.038
3     241 2011  23.931
4     155 2010  16.618
5      76 2009   8.736
6      34 2008   4.096
7       5 2007   0.640
8       0 2006   0.000
9       0 2005   0.000
10      0 2004   0.000
11      0 2003   0.000
12      0 2002   0.000
13      0 2001   0.000
14      0 2000   0.000
15      0 1999   0.000


Will become

   Number Year per100k
15      0 1999   0.000
14      0 2000   0.000
13      0 2001   0.000
12      0 2002   0.000
11      0 2003   0.000
10      0 2004   0.000
9       0 2005   0.000
8       0 2006   0.000
7       5 2007   0.640
6      34 2008   4.096
5      76 2009   8.736
4     155 2010  16.618
3     241 2011  23.931
2     342 2012  32.038
1     419 2013  37.394

No comments:

Post a Comment