Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transpose a tibble

Tags:

r

dplyr

tibble

I have this tibble:

tibble(Cor = c("Linear", "Rank"),
       `a,b` =  c("x1","x2"),
       `b,c` = c("x3","x4")
)

I want to transpose it into this tibble:

tibble(Cor = c("a,b","b,c"),
       Linear = c("x1","x3"),
       Rank = c("x2","x4")
)

Is there a tidyverse simple command to do so?

like image 389
GiulioGCantone Avatar asked Sep 07 '26 15:09

GiulioGCantone


2 Answers

We can do it in two steps with tidyr's pivot_longer and pivot_wider:

df %>%  
  pivot_longer(-Cor) %>%   
  pivot_wider(names_from = Cor, values_from = value) 
like image 63
Jon Spring Avatar answered Sep 10 '26 04:09

Jon Spring


We can use data.table::transpose

as_tibble(data.table::transpose(dat, make.names = 'Cor', keep.names = 'Cor'))
 # A tibble: 2 × 3
  Cor   Linear Rank 
  <chr> <chr>  <chr>
1 a,b   x1     x2   
2 b,c   x3     x4   

data

dat <- tibble(Cor = c("Linear", "Rank"),
       `a,b` =  c("x1","x2"),
       `b,c` = c("x3","x4")
)
like image 29
akrun Avatar answered Sep 10 '26 03:09

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!