Pivot_wider 并计算保留所有其他列的出现次数

Pivot_wider and count number of occurrences retaining all other columns

我要pivot_wider转专栏issue。该值应该是每个 issue 每个 product:

出现的次数
library(dplyr)
library(tidyr)

df = data.frame(product=  c(1,1,1,2,2,2,3,3,3),
                type = c(rep("a",3),rep("b", 3),rep("a",3)),
                issue = c("fall","fall","trap",
                          "trap", "jump", "fall",
                          "trap", "jump", "open"))

输出应该是

  product type fall trap jump open
1       1    a    2    1   NA   NA
2       2    b    1    1    1   NA
3       3    a   NA    1    1    1

我已经尝试了此处提供的答案:pivot_wider, count number of occurrences 但这不会保留其他列:

df%>%
  group_by(product)%>%
  pivot_wider(id_cols = "product", names_from = "issue", values_from = type, values_fn = list(type = length))


 product  fall  trap  jump  open
    <dbl> <int> <int> <int> <int>
1       1     2     1    NA    NA
2       2     1     1     1    NA
3       3    NA     1     1     1

还有其他方法吗?

你可以先数一下:

library(dplyr)
library(tidyr)

df = data.frame(product=  c(1,1,1,2,2,2,3,3,3),
                type = c(rep("a",3),rep("b", 3),rep("a",3)),
                issue = c("fall","fall","trap",
                          "trap", "jump", "fall",
                          "trap", "jump", "open"))
df %>% 
  count(product, type, issue) %>% 
  pivot_wider(names_from = issue,
              values_from = n)
#> # A tibble: 3 × 6
#>   product type   fall  trap  jump  open
#>     <dbl> <chr> <int> <int> <int> <int>
#> 1       1 a         2     1    NA    NA
#> 2       2 b         1     1     1    NA
#> 3       3 a        NA     1     1     1

reprex package (v2.0.1)

于 2022-05-25 创建