在dplyr中使用do或Summary创建绘图副作用

在dplyr中使用do或Summary创建绘图副作用,r,rstudio,dplyr,R,Rstudio,Dplyr,我正在使用do()将模型拟合到分组数据,然后我想为每个组绘制拟合图。在plyr中,我想我会使用d_ply()。在dplyr中,我尝试使用一个使绘图产生副作用的函数来执行do()或summary() 根据我使用的是do()还是summary(),我会得到不同的结果,我不知道为什么。具体来说,summary()似乎没有在每一行上正确运行 下面是我的例子: require(nycflights13) require(mgcv) # fit a gam to the flights grouped b

我正在使用
do()
将模型拟合到分组数据,然后我想为每个组绘制拟合图。在
plyr
中,我想我会使用
d_ply()
。在
dplyr
中,我尝试使用一个使绘图产生副作用的函数来执行
do()
summary()

根据我使用的是
do()
还是
summary()
,我会得到不同的结果,我不知道为什么。具体来说,
summary()
似乎没有在每一行上正确运行

下面是我的例子:

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))
require(nycflights13)
要求(mgcv)
#将gam安装到按目的地分组的航班(从?do)
按目的地%分组按(目的地)%>%筛选(n()>100)
模型=按目标%>%do(平滑=gam(arr\u delay~s(dep\u time)+月份,数据=))
#打印前4行,目标为ABQ、ACK、ALB、ATL
型号%>%切片(1:4)
#制作一个函数来绘制模型,标题为dest
plot.w.title=函数(title,gam.model){
plot.gam(gam.model,main=title)
报税表(1)
}
#此代码使用错误的标题进行绘图,例如ATL列出两次:
型号%>%
切片(1:4)%>%
行%>%
总结(无用.列=绘图.w.标题(目的地,平滑))#绘图副作用
#这段代码给了我正确的标题…为什么不同?
型号%>%
切片(1:4)%>%
行%>%
do(无用列=绘图w标题(.$dest,.$smooth))
如果对标题应用unique()修改函数,summary()方法将起作用:

plot.w.title = function(title, gam.model){
  plot.gam(gam.model, main=unique(title))
  return(1) 
}

当我运行summary()代码时,我没有两次看到ATL。我看到ABQ、ACK、ALB和ATL。您如何查看这些绘图?这可能是一个
RStudio
问题。当我使用
x11
或图形设备时,一切正常,但在
RStudio
图形设备中,我也遇到了同样的问题。它出现在RStudio图形设备上……我甚至没有想到这一点。谢谢行得通——谢谢!只是想知道--你觉得如何尝试独特?我应该知道rowwise或summary是如何工作的吗?我的想法是,假设您将title参数作为向量提供,即使您指定了rowwise。这就是为什么我尝试将其转换为单个值。考虑到其他人表示这是一个图形设备问题,unique工作的事实纯粹是运气:p