【问题标题】:creating plot side effects with do or summarise in dplyr在 dplyr 中使用 do 或 summarise 创建绘图副作用
【发布时间】:2015-04-27 00:26:19
【问题描述】:

我正在使用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))

【问题讨论】:

  • 当我运行 summarise() 代码时,我没有看到 ATL 两次。我看到 ABQ、ACK、ALB 和 ATL。您如何看待这些情节?
  • 这可能是RStudio 问题。当我使用x11 或图形设备时,一切正常,但在RStudio 图形设备中我遇到了同样的问题。
  • 它在 Rstudio 图形设备上……我什至没有想到。谢谢!

标签: r rstudio dplyr


【解决方案1】:

如果您通过将 unique() 应用于标题来修改函数,summarise() 方法将起作用:

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

【讨论】:

  • 这行得通——谢谢!只是想知道——你认为如何尝试独特?有什么我应该知道的关于如何按行或汇总的工作吗?
  • 我的想法是假设您将 title 参数作为向量提供,即使您已按行指定。这就是为什么我尝试 unique 将其转换为单个值。鉴于其他人已经表示这是一个图形设备问题,unique 工作的事实只是纯粹的运气:p
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-21
  • 1970-01-01
  • 2016-08-07
  • 1970-01-01
  • 2021-08-17
  • 1970-01-01
相关资源
最近更新 更多