如何使用map遍历mable中每个模型并调用gg_tsresiduals()
问题原因
gg_tsresiduals()要求输入的mable只能包含1个模型,你之前直接对整个mable调用map()时,默认是按列遍历,传入函数的是整列的State/Industry/模型向量,不是单行单模型的mable结构,所以触发报错。
解决方法
最简批量绘图
按行拆分mable为列表,每个元素为单模型mable后遍历绘图即可:
library(purrr) library(dplyr) ft.mod |> rowwise() |> group_split() |> map(\(x) gg_tsresiduals(x))
带分组标题的绘图
如果需要给每个图加上对应州、行业的标题方便区分,可以用pmap遍历每行字段:
ft.mod |> pmap(\(State, Industry, drift) { # 构造符合要求的单行mable tibble(State = State, Industry = Industry, drift = list(drift)) |> as_mable(key = c(State, Industry), model = drift) |> gg_tsresiduals() + ggtitle(paste(State, Industry, "漂移模型残差")) })
拼合所有残差图
如果需要把所有残差图整合到同一个画板展示,可以配合patchwork包实现:
library(patchwork) ft.mod |> rowwise() |> group_split() |> map(\(x) gg_tsresiduals(x)) |> wrap_plots(ncol = 2) # 调整ncol/nrow参数控制排版
内容的提问来源于stack exchange,提问作者Doug Fir
相关产品推荐
相关产品推荐

