如何按十年绘制时间序列tibble?floor_date报错排查
问题修复:处理yearmonth类型时间序列的十年分组错误
错误原因
你的代码存在三个问题:
index_by中直接使用tidy_ts$date不符合管道操作的上下文引用规则,应基于当前数据框的列进行引用;tidy_ts$date的类型是yearmonth(由as_tsibble()处理月度时间序列生成),而lubridate::floor_date()默认不支持该类型,触发unsupported_date_time()错误;- 代码最后一行多了一个多余的括号,会引发语法错误。
修复方案
针对yearmonth类型的时间列,有两种可靠的分组方式:
方案1:转换为Date类型后取整再转回yearmonth
先把yearmonth转换为标准Date类型,用floor_date()取整到十年起始,再转回yearmonth保持时间序列类型一致性:
# Graph the tidy data by decade tidy_ts %>% index_by( decade = ~ yearmonth(floor_date(as.Date(date), years(10))) ) %>% summarise(mean_s = mean(spots)) %>% ggplot(aes(decade, mean_s)) + geom_point() + geom_smooth() + ylab("Sunspots: Mean by Decade")
方案2:直接基于年份计算十年分组
提取年份后通过整数运算得到十年起始年份,再转换为yearmonth类型,避免类型转换的麻烦:
# Graph the tidy data by decade tidy_ts %>% index_by( decade = ~ yearmonth(paste(year(date) %/% 10 * 10, 1, sep = "-")) ) %>% summarise(mean_s = mean(spots)) %>% ggplot(aes(decade, mean_s)) + geom_point() + geom_smooth() + ylab("Sunspots: Mean by Decade")
额外说明
index_by()的表达式中,直接使用列名(如date)即可,无需引用整个数据框(tidy_ts$date),管道会自动传递当前数据上下文;- 确保移除原代码末尾的多余括号,否则会触发语法错误。
内容的提问来源于stack exchange,提问作者Kam
相关产品推荐
相关产品推荐

