My understanding was that to an extend, pivot_wider(data, names_from, values_from)
is roughly equivalent to spread(data, key, value)
. I'm not seeing that here.
library(tidyverse)
df = data.frame(
A = sample(letters[1:3], 20, replace=T),
B = sample(LETTERS[1:3], 20, replace=T)
)
df
#> A B
#> 1 c B
#> 2 b C
#> 3 b B
#> 4 b C
#> 5 c C
#> 6 b B
#> 7 c B
#> 8 b A
#> 9 c A
#> 10 b B
#> 11 c B
#> 12 b B
#> 13 b A
#> 14 c C
#> 15 c C
#> 16 a B
#> 17 c C
#> 18 b C
#> 19 b A
#> 20 a C
df %>% count(A,B)
#> A B n
#> 1 a B 1
#> 2 a C 1
#> 3 b A 3
#> 4 b B 4
#> 5 b C 3
#> 6 c A 1
#> 7 c B 3
#> 8 c C 4
df %>% count(A,B) %>% spread(key=B, value=n)
#> A B C
#> 1 NA 1 1
#> 2 3 4 3
#> 3 1 3 4
df %>% count(A,B) %>% pivot_wider(names_from=B, values_from=n)
#> Error: Failed to create output due to bad names.
#> * Choose another strategy with `names_repair`
Created on 2020-10-22 by the reprex package (v0.3.0)