Rotating or transposing R objects

Two dimensional R objects include data.frame, matrix and table objects. You can transpose the rows and columns using the t() command. Here is a simple data.frame:

> dat <- as.data.frame(matrix(1:12, ncol = 4))
> colnames(dat) <- LETTERS[1:4]
> dat
  A B C  D
1 1 4 7 10
2 2 5 8 11
3 3 6 9 12

You can rotate the data.frame so that the rows become the columns and the columns become the rows. That is, you transpose the rows and columns. You simply use the t() command.

> t(dat)
  [,1] [,2] [,3]
A    1    2    3
B    4    5    6
C    7    8    9
D   10   11   12

The result of the t() command is always a matrix object.

> dat.t <- t(dat)
> class(dat.t)
[1] "matrix"

You can also rotate a matrix object or a table, as long as the table only has 2 dimensions. These items will have rownames() and colnames() elements (even if empty). You can use the dim() command to look at the dimensions of an object.

> dim(HairEyeColor)
[1] 4 4 2

The HairEyeColor table has more than 2 dimensions and so will not rotate:

> t(HairEyeColor)
Error in t.default(HairEyeColor) : argument is not a matrix

However, you can get part of the table (as 2-dimensions):

> HEC <- as.table(HairEyeColor[,,1])
> HEC
       Eye
Hair    Brown Blue Hazel Green
  Black    32   11    10     3
  Brown    53   50    25    15
  Red      10   10     7     7
  Blond     3   30     5     8

> class(HEC)
[1] "table"

Now it can be rotated:

> t(HEC)
       Hair
Eye     Black Brown Red Blond
  Brown    32    53  10     3
  Blue     11    50  10    30
  Hazel    10    25   7     5
  Green     3    15   7     8

The colnames() and rownames() elements are preserved (but transposed of course), any names() attributes are lost (since the result is a matrix):

> HEC.t <- t(HEC)
> dimnames(HEC.t)
$Eye
[1] "Brown" "Blue"  "Hazel" "Green"

$Hair
[1] "Black" "Brown" "Red"   "Blond"

Summary

  • Use t() to rotate (transpose) frame, matrix or table objects with 2-dimensions.
  • Check the dimensions using dim().
  • The result is always a matrix.
  • The colnames() and rownames() attributes are preserved (but transposed).
  • Any names() attributes are lost.
Comments are closed.