How to transpose a dataframe in tidyverse?

43,273

Solution 1

Try with add_rownames

add_rownames(mtcars) %>% 
         gather(var, value, -rowname) %>% 
         spread(rowname, value) 

In the newer version, rownames_to_column replaces add_rownames

mtcars %>%
   rownames_to_column %>% 
   gather(var, value, -rowname) %>% 
   spread(rowname, value) 

In the even newer version, pivot_wider replaces spread:

mtcars %>%
   tibble::rownames_to_column() %>%  
   pivot_longer(-rowname) %>% 
   pivot_wider(names_from=rowname, values_from=value) 

Solution 2

There's now a purpose-built function to do this, rotate_df() from sjmisc.

library(sjmisc)
mtcars %>% rotate_df()

#     Mazda RX4 Mazda RX4 Wag Datsun 710 Hornet 4 Drive Hornet Sportabout Valiant Duster 360
#mpg      21.00        21.000      22.80         21.400             18.70   18.10      14.30
#cyl       6.00         6.000       4.00          6.000              8.00    6.00       8.00
#disp    160.00       160.000     108.00        258.000            360.00  225.00     360.00
#hp      110.00       110.000      93.00        110.000            175.00  105.00     245.00
#drat      3.90         3.900       3.85          3.080              3.15    2.76       3.21

#etc

The function also allows you to convert rownames to real df data with the rotate. Many thanks to the package creators.

Share:
43,273
Irakli
Author by

Irakli

Updated on January 13, 2022

Comments

  • Irakli
    Irakli over 2 years

    Using basic R, I can transpose a dataframe, say mtcars, which has all columns of the same class:

    as.data.frame(t(mtcars))
    

    Or with pipes:

    library(magrittr)
    mtcars %>% t %>% as.data.frame
    

    How to accomplish the same within tidyr or tidyverse packages?

    My attempt below gives:

    Error: Duplicate identifiers for rows

    library(tidyverse)
    mtcars %>% gather(var, value, everything()) %>% spread(var, value)