Move table using reshape2

I have this data.frame:

mtcars_sub <- mtcars[1:5,c("mpg", "disp")]
mtcars_sub$car <- rownames(mtcars_sub)
rownames(mtcars_sub) <- 1:5
mtcars_sub

   mpg disp               car
1 21.0  160         Mazda RX4
2 21.0  160     Mazda RX4 Wag
3 22.8  108        Datsun 710
4 21.4  258    Hornet 4 Drive
5 18.7  360 Hornet Sportabout

I need the data.frame to be converted to this format:

enter image description here

I specifically after the answer that uses the package reshape2

+4
source share
1 answer

Here is what you are looking for:

> library(reshape2)
> dcast(melt(mtcars_sub), variable~car)
Using car as id variables
  variable Datsun 710 Hornet 4 Drive Hornet Sportabout Mazda RX4 Mazda RX4 Wag
1      mpg       22.8           21.4              18.7        21            21
2     disp      108.0          258.0             360.0       160           160

alternatively you can use ...to replacevariable

>dcast(melt(mtcars_sub), ...~car)
+4
source

All Articles