转置小标题

Transpose a tibble

我有这个问题:

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

我想把它转变成这个小标题:

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

有简单的 tidyverse 命令吗?

我们可以使用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   

数据

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

我们可以用 tidyrpivot_longerpivot_wider 分两步完成:

df %>%  
  pivot_longer(-Cor) %>%   
  pivot_wider(names_from = Cor, values_from = value) 

更快的方法是在管道 %>%

之后使用 R 基函数 t()
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"