Use t using apply to apply a non…


asthmatically Use t() using apply() to apply a non-aggregate function on a matrix row wise because column wise is the default order of matrix in R.

singlar blou met du lait Example.
I’d like to reverse the order of elements in each row.

> test.m <- matrix(1:20, nrow = 4) > test.m [,1] [,2] [,3] [,4] [,5] [1,] 1 5 9 13 17 [2,] 2 6 10 14 18 [3,] 3 7 11 15 19 [4,] 4 8 12 16 20

Apply will put the results in column wise manner.

> apply(test.m, 1, rev)
[,1] [,2] [,3] [,4]
[1,]   17   18   19   20
[2,]   13   14   15   16
[3,]    9   10   11   12
[4,]    5    6    7    8
[5,]    1    2    3    4

To get the right answer, I need transformation.

> t(apply(test.m, 1, rev))
[,1] [,2] [,3] [,4] [,5]
[1,]   17   13    9    5    1
[2,]   18   14   10    6    2
[3,]   19   15   11    7    3
[4,]   20   16   12    8    4

On the other hand, if I want to reverse the order of elements in column, t() is not necessary.

> apply(test.m, 2, rev)
[,1] [,2] [,3] [,4] [,5]
[1,]    4    8   12   16   20
[2,]    3    7   11   15   19
[3,]    2    6   10   14   18
[4,]    1    5    9   13   17

Leave a Reply

Your email address will not be published. Required fields are marked *