本文介绍了ivot_wider在同一行上合并信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

数据就像:

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

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)

预期的输出为

推荐答案

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

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

这篇关于ivot_wider在同一行上合并信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 23:47