pivoting dataframe with dplyr

Hello,

I need to pivot from this table:

(multi <- tribble(
  ~id, ~type, ~sum1, ~sum2,
  1,  0,7, 8,
  1,  1,52, 100,
  3,  0, 0, 20,
  3,  1,25, 80,
  4,  0, 7, 0,
  4,  1, 12, 13,
  5,  0, 0, 32,
  5,  1, 13, 13
))

Here is the picture of the above dataset:

To this one:

(multi2 <- tribble(
  ~id,  ~sum1, ~sum1_1, ~sum2, ~sum2_1,
  1,  7, 52, 8, 100,
  3,   0, 25, 20, 80,
  4,   7, 12, 0, 13,
  5,   0, 13, 32, 13,
))

This is the picture of the output dataset:

Can someone show me how to do it with the new pivot_wider() function from dplyr?

Thanks in advance,
Sebastian

The pivot_ functions are actually in tidyr.

This is one way:
tidyr::pivot_wider(multi, names_from = type, values_from = starts_with("sum"))

5 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.