Irakli Irakli - 1 month ago 17
R Question

R: How to transpose a dataframe in tidyverse?

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

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)

Answer

Try with add_rownames

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