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)
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)).
To change the row order in an R data frame, we can use single square brackets and provide the row order at first place.
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) .
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With