Transposing matrices
One of the most used, but often not mentioned, methods for restructuring data is transposing matrices. This simply means switching the columns with rows and vice versa, via the t
function:
> (m <- matrix(1:9, 3)) [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 > t(m) [,1] [,2] [,3] [1,] 1 2 3 [2,] 4 5 6 [3,] 7 8 9
Of course, this S3
method also works with data.frame
, and actually, with any tabular object. For more advanced features, such as transposing a multi-dimensional table, take a look at the aperm
function from the base
package.