【发布时间】:2023-02-11 09:09:10
【问题描述】:
我有一个数据集,其中包含每年的一系列观察结果。我只想按年计算“失败”和“参加”的百分比,然后在同一个图上用 geom_line() 绘制年度趋势。我开始使用下面的代码,但它不太正确——我认为它需要按年份折叠?
代码:
df %>%
group_by(year) %>%
mutate(perc_fail = fail/sum(fail),
perc_attend = attend/sum(attend)) %>%
ggplot(., aes(x = year)) +
geom_line()
数据:
df < -structure(list(year = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
4L, 4L, 4L, 4L, 4L), .Label = c("2000", "2001", "2002", "2003"
), class = "factor"), fail = c(0, 0, 0, 0, 0, 1, 1, 0, 0, 0,
1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1,
0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0,
0, 0, 1, 1, 0, 0, 0, 0), attend = c(1, 1, 1, 1, 1, 0, 0, 1, 1,
1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1,
1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1)), row.names = c(NA, -60L), spec = structure(list(
cols = list(year = structure(list(), class = c("collector_double",
【问题讨论】: