Irakli Irakli - 2 months ago 33
R Question

R: How to transpose a dataframe in tidyverse?

Using the basic R, I can transpose a dataframe, say mtcars:

Or with pipes:

mtcars %>% t %>%

How to accomplish the same within tidyr or tidyverse packages?

My attempt below gives "Error: Duplicate identifiers for rows"

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


Try with add_rownames

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