错误:mutate_impl(.data, dots) 中的错误:列"three_month"的长度

  • 本文关键字:错误 quot month three impl mutate data dots r dplyr
  • 更新时间 :
  • 英文 :


我的每周数据集具有与不同城市相关的不同state_id。值 1 和值 2 需要聚合到每月级别,然后聚合到季度级别。所以我尝试下面的代码:

library(dplyr)  
df <- dataset %>%
group_by(state_id,city_id) %>%
group_by(three_month = round_date(weekly_dt, "quarter")) %>%   
summarise_at(vars(starts_with('value')), mean)

但它弹出了这个错误

Error in mutate_impl(.data, dots) : 
Column `three_month` must be length 1 (the group size), not 3766742

注意:所有城市都没有相同级别的每周数据,这就是我首先使用group_by的原因。 有人可以在R中帮助我吗? 编辑:我的数据

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>)

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

相关内容

最新更新