简体   繁体   English

R dplyr-按月分组的传播频率

[英]R dplyr - spreading frequencies of grouping by month

I would like to group my df by month and year. 我想按月和年对我的df分组。 The outcome should be counted, frequencies for 0 and 1. I can get the overall frequencies but can't spread it. 应该计算结果,频率为0和1。我可以得到总体频率,但不能传播它。 The issue is the last line of code. 问题是代码的最后一行。 I get the error message at the bottom. 我在底部收到错误消息。

id <- 1:1000
outcome <- rbinom(1000, 1, 0.23)
date <- sample(seq(as.Date('2000/01/01'), as.Date('2002/12/31'), by="day"), 1000)
df <- data.frame(id, date, outcome)

library(dplyr)
library(tidyr)

df_month<- df%>%
    mutate(month = format(date, "%m"), year = format(date, "%Y")) %>%
    group_by(month, year) %>%
    summarise(freq = n())%>%
    spread(outcome, freq)

Error: var must evaluate to a single number or a column name, not an integer vector 错误: var必须求值为单个数字或列名,而不是整数向量

I think this is what you need - 我认为这就是您需要的-

df_month <- df %>%
  mutate(month = format(date, "%m"), year = format(date, "%Y")) %>%
  group_by(month, year, outcome = paste0("outcome_", outcome)) %>%
  summarise(freq = n()) %>%
  spread(outcome, freq)

# A tibble: 36 x 4
# Groups:   month, year [36]
   month year  outcome_0 outcome_1
   <chr> <chr>     <int>     <int>
 1 01    2000         18        10
 2 01    2001         22         3
 3 01    2002         22         6
 4 02    2000         20         8
 5 02    2001         21         4
 6 02    2002         22         5
 7 03    2000         20         9
 8 03    2001         24         5
 9 03    2002         26         3
10 04    2000         19         9
# ... with 26 more rows

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM