4

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

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)
}
4

1 回答 1

11

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

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

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

augment()无论如何,通常建议这样做,因为model.frame()不会获得所有原始列。


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

相反,我建议使用 tidyr'snest()和 purrr's map(),如R4DS 本章所述。这使得保留数据和合并到augment().

library(tidyr)
library(purrr)

mtcars %>%
  nest(-cyl) %>%
  mutate(fit = map(data, ~ loess(wt ~ mpg, .))) %>%
  unnest(map2(fit, data, augment))
于 2018-04-02T18:33:30.643 回答