使用扫帚(增强)和dplyr与黄土适合时出错

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用扫帚(增强)和dplyr与黄土适合时出错相关的知识,希望对你有一定的参考价值。

我试图在黄土适合使用扩充,但我收到以下错误:

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)
}
答案

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

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

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

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


顺便说一句,我是扫帚的维护者,我一般不再推荐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))

以上是关于使用扫帚(增强)和dplyr与黄土适合时出错的主要内容,如果未能解决你的问题,请参考以下文章

一个接一个地加载 Data.Table 和 dplyr 会出错

如何按组进行汇总并使用R中的dplyr获取总体数据集的摘要

如何使用 R 在校准图中添加黄土线、斜率和截距?

python之面向对象与实例属性

面向对象编程与面向过程变成之间的比较

DPLYR 中汇总的奇怪行为