0

I have a dataframe which i am trying to transpose .But when I do that it converts it into a matrix. How do I transpose a dataframe without changing it to a matrix.

Actual Dataframe:

  Month_considered Exclusive Loyal Interacting loyal left Non loyal Switcher Total
1            Apr-17              11               632  479       910      229  1782
2            Aug-17              35               613  830      1014      241  1903
3            Dec-17              35               683  757      1205      122  2045
4            Feb-18               0                 0    0         0        0     0
5            Jan-18              36               708  684      1085      297  2126
6            Jul-17              30               560  631      1072      231  1893

df%>%t()

                 [,1]     [,2]     [,3]     [,4]     [,5]     [,6]     [,7]     [,8]     [,9]     [,10]    [,11]   
Month_considered  "Apr-17" "Aug-17" "Dec-17" "Feb-18" "Jan-18" "Jul-17" "Jun-17" "May-17" "Nov-17" "Oct-17" "Sep-17"
Exclusive Loyal   "11"     "35"     "35"     " 0"     "36"     "30"     "29"     "34"     "43"     "42"     "32"    
Interacting loyal "632"    "613"    "683"    "  0"    "708"    "560"    "493"    "640"    "577"    "572"    "605"   
left              "479"    "830"    "757"    "  0"    "684"    "631"    "609"    "503"    "667"    "719"    "645"  
SNT
  • 1,283
  • 3
  • 32
  • 78
  • 2
    A dataframe is by definition a collection of columns. Transposing logically means that you need it row-oriented, which is not a logical thing in R. Is this just for presentation, or is there a reason you need to have it row-primary? – r2evans Aug 07 '18 at 15:10
  • Presentation only – SNT Aug 07 '18 at 15:12
  • 1
    What is your concern if it is a matrix, then? If your presentation is for the console, then it's just up to you to deal with the extra quotation marks (you can generate your own `print.*` method if desired). If it's for a report, then something like `knitr::kable` deals just fine with transposed matrices. For example, `knitr::kable(t(mtcars[1:5,1:3]))`. – r2evans Aug 07 '18 at 15:14
  • 2
    What's the problem if you use `as.data.frame(t(df))`? – antonioACR1 Aug 07 '18 at 15:16
  • Providing code to reproduce the "actual dataframe" from your example would help, along with info on what exactly you'd expect to see instead of `t(df)` for the example. Some guidance: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/28481250#28481250 – Frank Aug 07 '18 at 15:19

1 Answers1

1

You can use transpose from the data.table package.

data.table::transpose(mydf)

this should work.