如何获取总行数和具有“1”值的行数,在 r 中按月分组?

How to get a total number of rows and of rows that have '1' value, grouping by month in r?

我有一个数据集。例如,2016 年的数据。

假设从 2016 年 1 月 1 日到 12 月 31 日有 365 个观测值。每天,数据都包含 1 或 0。

我正在尝试计算每个月的百分比。

感谢专家的帮助!

这应该有效:

df = data.frame(date=seq(as.Date("2017-01-01"),as.Date("2017-12-31"),by=1) , value=sample(c(0,1),365,replace=T) )

library(dplyr)
df  = df %>% mutate(month = format(date,"%m")) %>%  # or %b for month abbreviation
group_by(month) %>% 
summarize(value=sum(value)/length(value))