Transpose a tibble

Viewed 162

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?

3 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) 

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")
)

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"
Related