【问题标题】:Error when using broom (augment) and dplyr with loess fit使用带黄土的扫帚(增强)和 dplyr 时出错
【发布时间】:2018-09-11 23:17:54
【问题描述】:

我正在尝试在黄土上使用增强,但收到以下错误:

Error in data.frame(..., check.names = FALSE) : 
  arguments imply differing number of rows: 32, 11

在错误消息中,11 恰好等于一个片段中的观察数,而 32 是观察总数。代码如下。

require(broom)
require(dplyr)

# This example uses the lm method and it works
regressions <- mtcars %>% group_by(cyl) %>%  do(fit = lm(wt ~ mpg, .))
regressions %>% augment(fit)

# This example uses the loess method and it generates the error
regressions2 <- mtcars %>% group_by(cyl) %>%  do(fit = loess(wt ~ mpg, .))
regressions2 %>% augment(fit)

# The below code appropriately plots the loess fit using geom_smooth. 
# My current # workaround is to do a global definition as an aes object in geom_smooth`
cylc = unique(mtcars$cyl) %>% sort()
for (i in 1:length(cyl)){
  print(i)
  print(cyl[i])
  p<- ggplot(data=filter(mtcars,cyl==cylc[i]),aes(x=mpg,y=wt)) + geom_point() + geom_smooth(method="loess") + ggtitle(str_c("cyl = ",cyl[i]))
  print(p)
}

【问题讨论】:

    标签: r dplyr broom


    【解决方案1】:

    这似乎是与 do() 运算符有关的问题:当我们检查一个 LOESS 模型对象上的 model.frame() 时,我们会返回所有 32 行而不是对应于该模型的子集。

    一种解决方法是保留数据而不仅仅是模型,并将其作为第二个参数传递给augment()

    regressions2 <- mtcars %>%
      group_by(cyl) %>%
      do(fit = loess(wt ~ mpg, .),
         data = (.)) %>%
       augment(fit, data)
    

    无论如何,通常建议使用augment(),因为model.frame() 不会获取所有原始列。


    顺便说一句,我是 broom 的维护者,我一般不再推荐 do() 方法(因为 dplyr 大部分时间都在远离它)。

    相反,我建议使用 tidyr 的 nest() 和 purrr 的 map(),如 this chapter of R4DS 中所述。这样可以更轻松地保留数据并合并到augment()

    library(tidyr)
    library(purrr)
    
    mtcars %>%
      nest(-cyl) %>%
      mutate(fit = map(data, ~ loess(wt ~ mpg, .))) %>%
      unnest(map2(fit, data, augment))
    

    【讨论】:

    • 感谢大卫的详细回复。我阅读了那一章,解决方案清晰而明智。您可能需要考虑在此处更新小插图:cran.r-project.org/web/packages/broom/vignettes/…,因为这是我使用 do() 的来源。
    • @Steve 你是完全正确的!有一些维护扫帚的新计划和资源意味着这些更新可能会在今年夏天发生
    • 太棒了。再次感谢您的帮助!
    • 作为可重现的解决方案,添加 library(tidyverse)、library(broom)。
    猜你喜欢
    • 2021-11-05
    • 2018-10-14
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 1970-01-01
    • 2012-05-18
    相关资源
    最近更新 更多