5

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?

GiulioGCantone
  • 195
  • 1
  • 10

3 Answers3

4

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) 
Jon Spring
  • 55,165
  • 4
  • 35
  • 53
  • would this preserve the name of the variable Cor as "Cor"? As much as I hate to mix tidyverse and data.table code, I feel that data.table::transpose is just more straightforward. – GiulioGCantone Feb 06 '22 at 17:49
3

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")
)
akrun
  • 874,273
  • 37
  • 540
  • 662
0

A faster approach is just using the R base function t() after a pipe %>%

df = tibble(Cor = c("Linear", "Rank"),
       `a,b` =  c("x1","x2"),
       `b,c` = c("x3","x4")
)
df_t = df %>% t()
df_t
    [,1]     [,2]  
Cor "Linear" "Rank"
a,b "x1"     "x2"  
b,c "x3"     "x4"
rubengavidia0x
  • 501
  • 1
  • 5
  • 18