Home > Mobile >  pivot wider from long dataframe
pivot wider from long dataframe

Time:05-11

I have:

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

And I want

enter image description here

I tried df %>% pivot_wider(names_from = metric, values_from = value) %>% select(-row), but this returns

enter image description here

CodePudding user response:

Remove row first, i.e.

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   

CodePudding user response:

We can also specify 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 

CodePudding user response:

the data.table approach

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