23
votes

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)
1
If you want to transpose it it should be a matrix and not a data.frame. What's wrong with using t? - Roland
Try add_rownames(mtcars) %>% gather(var, value, -rowname) %>% spread(rowname, value) - akrun
Why do you want to do this? You cannot meaningfully transpose a data.frame that contains many variable classes without loss of information. - Thomas
A data frame, such as mtcars, might have all columns of the same class. - Irakli

1 Answers

56
votes

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)