我正在使用do()
将模型拟合到分组数据,然后我想绘制每个组的拟合。在plyr
中,我想我会使用d_ply()
。在dplyr
中,我正在尝试使用使得绘图成为副作用的函数do()
或summarise()
。
我的结果会有所不同,具体取决于我使用的是do()
还是summarise()
,而且我不确定原因。具体来说,似乎summarise()
没有正确地在每一行上运行。
这是我的例子:
require(nycflights13)
require(mgcv)
# fit a gam to the flights grouped by dest (from ?do)
by_dest <- flights %>% group_by(dest) %>% filter(n() > 100)
models = by_dest %>% do(smooth = gam(arr_delay ~ s(dep_time) + month, data = .))
# print the first 4 rows, the dest is ABQ, ACK, ALB, ATL
models %>% slice(1:4)
# make a function to plot the models, titled by dest
plot.w.title = function(title, gam.model){
plot.gam(gam.model, main=title)
return(1)
}
# This code makes plots with the wrong titles, for example ATL is listed twice:
models %>%
slice(1:4) %>%
rowwise %>%
summarise(useless.column = plot.w.title(dest, smooth)) # for plot side effect
# this code gives me the correct titles...why the difference?
models %>%
slice(1:4) %>%
rowwise %>%
do(useless.column = plot.w.title(.$dest, .$smooth))
答案 0 :(得分:1)
如果通过对标题应用unique()来修改函数,则summarize()方法将起作用:
plot.w.title = function(title, gam.model){
plot.gam(gam.model, main=unique(title))
return(1)
}