从长数据框转向更宽

pivot wider from long dataframe

我有:

df = tibble(row = 1:10,
            n = as.character(c(1,1,1,1,1, rep(2,5))),
           n2 = n,
           metric = rep(LETTERS[1:5],2),
           value = as.character(c(1:10)))

我想要

我试过了 df %>% pivot_wider(names_from = metric, values_from = value) %>% select(-row),但是这个returns

先去掉row,即

library(dplyr)
library(tidyr)

df %>% 
 select(-row) %>% 
 pivot_wider(names_from = metric, values_from = value)

 n     n2    A     B     C     D     E    
  <chr> <chr> <chr> <chr> <chr> <chr> <chr>
1 1     1     1     2     3     4     5    
2 2     2     6     7     8     9     10   

我们也可以指定id_cols:

df %>% 
  pivot_wider(id_cols = c(n, n2), names_from = metric, values_from = value)
# A tibble: 2 × 7
  n     n2    A     B     C     D     E    
  <chr> <chr> <chr> <chr> <chr> <chr> <chr>
1 1     1     1     2     3     4     5    
2 2     2     6     7     8     9     10 

data.table 方法

library(data.table)
dcast(setDT(df), n + n2 ~ metric, value.var = "value")
#    n n2 A B C D  E
# 1: 1  1 1 2 3 4  5
# 2: 2  2 6 7 8 9 10