I would like to group my df by month and year. The outcome should be counted, frequencies for 0 and 1. I can get the overall frequencies but can't spread it. 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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.