Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transpose a dataframe in tidyverse?

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)
like image 668
Irakli Avatar asked Oct 28 '16 13:10

Irakli


People also ask

How do I switch rows and columns of a Dataframe in R?

Thus, to convert columns of an R data frame into rows we can use transpose function t. For example, if we have a data frame df with five columns and five rows then we can convert the columns of the df into rows by using as. data. frame(t(df)).

How do I switch rows in a Dataframe in R?

To change the row order in an R data frame, we can use single square brackets and provide the row order at first place.

How do I transpose columns in R?

Which function is used to create a transpose of a given matrix in R? To interchange rows with columns, you can use the t() function. For example, if you have the matrix (or dataframe) mat you can transpose it by typing t(mat) .


2 Answers

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) 
like image 183
akrun Avatar answered Oct 16 '22 20:10

akrun


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.

like image 21
Joe Avatar answered Oct 16 '22 19:10

Joe