Search code examples
rdataframetranspose

How to rotate in R?


I have a data frame that looks like below and I want to rotate. I use t() function in R, but I the direction where I want to rotate the data frame is different from the desired output. Please find the snippet of my code below:

 x<-data.frame(x=c(1,4,5,6,7),y=c(5,7,8,5,9))

> x
  x y
1 1 5
2 4 7
3 5 8
4 6 5
5 7 9
> t(x)
  [,1] [,2] [,3] [,4] [,5]
x    1    4    5    6    7
y    5    7    8    5    9

Rather, i want the following output:

    [,1] [,2] [,3] [,4] [,5]
 y    5    7    8    5    9
 x    1    4    5    6    7

How can i achieve this in R?


Solution

  • You can reverse and transpose at the same time

    t(rev(x))
    #   [,1] [,2] [,3] [,4] [,5]
    # y    5    7    8    5    9
    # x    1    4    5    6    7