0

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

Dre Day
  • 338
  • 2
  • 8

4 Answers4

1

Here is an alternative approach without pivoting:

library(janitor)
library(dplyr)
df %>% 
  t() %>% 
  row_to_names(row_number = 1) %>% 
  as.data.frame()
     a  b  c  d  e
jan  1  2  3  4  5
feb  2  4  6  8 10
mar  3  6  9 12 14
TarJae
  • 72,363
  • 6
  • 19
  • 66
0

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
arg0naut91
  • 14,574
  • 2
  • 17
  • 38
0

Please check this

df %>% pivot_longer(c(-1), names_to = 'name', values_to = 'value') %>% 
pivot_wider(names_from = model, values_from = value) %>% 
  rename(month=name)

Created on 2023-01-29 with reprex v2.0.2

# 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

jkatam
  • 2,691
  • 1
  • 4
  • 12
0

Thank you -

I ended up going with

df %>% 
    pivot_longer(cols = jan:mar) %>% 
    pivot_wider(names_from = model, values_from = value)

  name      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
Dre Day
  • 338
  • 2
  • 8