2

I want to use pivot_wider to create a wide list for a single date.

There are 8 different groups for one variable but the other variable is a summation.

data is like:

df <- data.frame(
  stringsAsFactors = FALSE,
  date = c("09/01/2020","09/01/2020",
           "09/01/2020","09/01/2020","09/01/2020","09/01/2020",
           "09/01/2020","09/01/2020"),
  x = letters[1:8],
  y = c(34L, 34L, 74L, 50L, 64L, 19L, 25L, 21L),
  z = c(42L, 210L, 284L, 145L, 125L, 77L, 70L, 70L)
)

when using pivot_wider it creates 7 rows instead of 8 as the first two observations of y are 34 as below

df %>% 
  pivot_wider(names_from = x, values_from = z, values_fill = 0)

whereas the intended output is enter image description here

0

1 Answer 1

2

While using pivot_wider it is making y column as id variable hence the row gets combined. Give every row a separate id and then get data in wide format.

library(dplyr)

df %>%
  mutate(row = row_number()) %>%
  tidyr::pivot_wider(names_from = x, values_from = z, values_fill = 0) %>%
  select(-row)

#  date           y     a     b     c     d     e     f     g     h
#  <chr>      <int> <int> <int> <int> <int> <int> <int> <int> <int>
#1 09/01/2020    34    42     0     0     0     0     0     0     0
#2 09/01/2020    34     0   210     0     0     0     0     0     0
#3 09/01/2020    74     0     0   284     0     0     0     0     0
#4 09/01/2020    50     0     0     0   145     0     0     0     0
#5 09/01/2020    64     0     0     0     0   125     0     0     0
#6 09/01/2020    19     0     0     0     0     0    77     0     0
#7 09/01/2020    25     0     0     0     0     0     0    70     0
#8 09/01/2020    21     0     0     0     0     0     0     0    70

Not the answer you're looking for? Browse other questions tagged or ask your own question.