Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I'm not writing my pivot_wider function correctly

I am trying to run pivot_wider so that the output switches the rows and column fields. This does not accomplish that – what am I missing here?

Current:

model jan feb mar
a     1   2   3   
b     2   4   6   
c     3   6   9   
d     4   8   12
e     5   10  14

Attempting:
month a b c d  e  f
jan   1 2 3 4  5  6
feb   2 4 6 8  10 12
mar   3 6 9 12 14
df <- data.frame(model = c('a', 'b', 'c', 'd', 'e'),
                 jan = c(1, 2, 3, 4, 5),
                 feb = c(2, 4, 6, 8, 10),
                 mar = c(3, 6, 9, 12, 14)
)

df %>% 
  pivot_wider(names_from = model, values_from = c(2:4), values_fill = 0)

My real set has around 15 columns and I’m just trying to flip the values and keep them tied to model and month fields. I am trying to get the values to play nicer with PowerBI so I can sort/filter/group in visuals by date values. Thank you

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could try:

library(tidyr)

df %>%
  pivot_longer(cols = -model, names_to = 'month') %>%
  pivot_wider(names_from = model)

Output:

# A tibble: 3 × 6
  month     a     b     c     d     e
  <chr> <dbl> <dbl> <dbl> <dbl> <dbl>
1 jan       1     2     3     4     5
2 feb       2     4     6     8    10
3 mar       3     6     9    12    14
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading