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

时间:2018-12-03 23:44:48

标签: r dplyr

我想按月和年对我的df分组。应该计算结果,频率为0和1。我可以得到总体频率,但不能传播它。问题是代码的最后一行。我在底部看到错误消息。

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)
  

错误:var必须计算为单个数字或列名,而不是   整数向量

1 个答案:

答案 0 :(得分:1)

我认为这是您需要的-

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