[英]R dplyr - spreading frequencies of grouping by month
我想按月和年對我的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
必須求值為單個數字或列名,而不是整數向量
我認為這就是您需要的-
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.