ivot_wider在同一行上合并信息

时间:2020-10-02 09:34:46

标签: r dplyr tidyverse tidyr

我想使用pivot_wider为单个日期创建一个广泛的列表。

一个变量有8个不同的组,而另一个变量是一个求和。

数据就像:

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)
)

使用pivot_wider时,它将创建7行而不是8行,因为y的前两个观测值如下所示34

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

预期输出为enter image description here

1 个答案:

答案 0 :(得分:2)

使用pivot_wider时,会将y列作为id变量,因此该行被合并。为每行指定一个单独的ID,然后获取宽格式的数据。

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