I would like to reorder the columns grouping by names_from
instead of values_from
, here is my minimal example:
mtcars %>%
tidyr::pivot_wider(names_from = gear, values_from = c(vs, am, carb))
output:
mpg cyl disp hp drat wt qsec vs_4 vs_3 vs_5 am_4 am_3 am_5 carb_4 carb_3 carb_5
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 21 6 160 110 3.9 2.62 16.5 0 NA NA 1 NA NA 4 NA NA
2 21 6 160 110 3.9 2.88 17.0 0 NA NA 1 NA NA 4 NA NA
3 22.8 4 108 93 3.85 2.32 18.6 1 NA NA 1 NA NA 1 NA NA
Here is what I want the output:
mpg cyl disp hp drat wt qsec vs_4 am_4 carb_4 vs_3 am_3 carb_3 vs_5 am_5 carb_5
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 21 6 160 110 3.9 2.62 16.5 0 1 4 NA NA NA NA NA NA
2 21 6 160 110 3.9 2.88 17.0 0 1 4 NA NA NA NA NA NA
Thanks in advance!
See Question&Answers more detail:os