我的每周数据集具有与不同城市关联的不同state_id.Value1和value2需要先汇总到每月级别,然后再汇总到季度级别,所以请尝试以下代码:
Error in mutate_impl(.data, dots) :
Column `three_month` must be length 1 (the group size), not 3766742
但是它会弹出此错误
structure(list(city_id = c("B02", "B02", "B02",
"B02", "B02", "B02"), state_id = c(609L, 609L,
609L, 609L, 609L, 609L), weekly_dt = structure(c(17601,
17545, 17447, 17727, 17510, 17664), class = "Date"), value1 = c(0.194669883125,
0.35, 0.35, 0.124875972916667, 0.35, 0.140909438125), value2 = c(0.203018924883721,
0.35, 0.35, 0.35, 0.35, 0.35)), class = c("data.table", "data.frame"
), row.names = c(NA, -6L), .internal.selfref = <pointer: 0x0000000004541ef0>)
注意:所有城市的每周数据水平都不相同,这就是我首先使用group_by的原因。 有人可以在R中帮助我吗? 编辑:我的爸爸
$tx
答案 0 :(得分:1)
mutate函数将其他列添加到数据帧,然后可以在group_by中引用。用floor_date
代替round_date
可能更好,因为该季度中的所有日期都将放在同一季度中。
library(dplyr)
library(lubridate)
df <- dataset %>%
mutate(three_month = floor_date(weekly_dt, "quarter")) %>%
group_by(state_id, city_id, three_month) %>%
summarise_at(vars(starts_with('value')), mean)
# A tibble: 4 x 5
# Groups: state_id, city_id [?]
# state_id city_id three_month value1 value2
# <int> <chr> <date> <dbl> <dbl>
# 1 609 B02 2017-10-01 0.350 0.350
# 2 609 B02 2018-01-01 0.272 0.277
# 3 609 B02 2018-04-01 0.141 0.350
# 4 609 B02 2018-07-01 0.125 0.350