tidyverse / modelr

Helper functions for modelling
https://modelr.tidyverse.org
GNU General Public License v3.0
401 stars 66 forks source link

add_predictions() with categorical variables (factors) in nls model #95

Closed rungec closed 10 months ago

rungec commented 5 years ago

Hi, When adding nls model predictions to tibble, where nls model includes categorical variable (a factor) add_predictions() seems to assume the tibble is ordered by that factor. see example below. Works fine for glm models though, so wasn't sure whether to post here or on the nls pages. Claire

require(tidyverse)

mtcars_tibble <- as_tibble(mtcars) %>% mutate(cyl=as.factor(cyl))

lf <- formula(mpg ~ exp(a+b*wt)| cyl)
mod1 <- nlme::nlsList(lf, data=mtcars_tibble, start=list(a=0,b=0))

mtcars_preds <- mtcars_tibble %>% add_predictions(mod1)

ggplot(mtcars_preds, aes(y=mpg, x=wt, group=cyl))+
  geom_point() +
  geom_line(aes(y=pred), col="red") +
  facet_wrap("cyl")

#adding arrange fixes the problem
mtcars_preds <- mtcars_tibble %>% arrange(cyl) %>% add_predictions(mod1)

ggplot(mtcars_preds, aes(y=mpg, x=wt, group=cyl))+
  geom_point() +
  geom_line(aes(y=pred), col="red") +
  facet_wrap("cyl")
hadley commented 10 months ago

modelr is now superseded, which means that we'll only perform critical bug fixes needed to keep it on CRAN. Thanks for contributing this idea and my apologies that it took so long to inform you that this package is no longer under development.