Skip to content

as.ggplot() whithin functions shows error #14

@chagas98

Description

@chagas98

I wanted to code a simple function to check lm() and glm() models using the DHARMa package, which results in r-base plots. So I was using as.ggplot() to convert it into a ggplot object. This procedure worked well until I gathered a function like this:

check_models <- function(cm, modeltype) {

  if (modeltype == "lm"){
    
    qqres <-  ggplot(cm, aes(sample = rstudent(cm))) +
      geom_qq() + 
      stat_qq_line() +
      xlab("Theoretical Quantiles") +
      ylab("Studentized Residuals") +
      ggtitle("Q-Q Plot") +
      theme_bw()
    
    denres <- ggplot(cm) + 
      geom_density(aes(x = residuals(cm))) +
      xlab("Residuals") +
      ylab("Density") +
      ggtitle("Density") +
      theme_bw()
    return(qqres+denres)
    }

  if (modeltype == "glm"){

    cm_simres <- DHARMa::simulateResiduals(fittedModel = cm, n = 250)
    print(cm_simres)
    plot1 <- ggplotify::as.ggplot(~plot(cm_simres, asFactor = FALSE))
    
    cm_simres_refit <- DHARMa::simulateResiduals(fittedModel = cm,
                                                   n = 250,
                                                   refit = TRUE)
    plot2 <- ggplotify::as.ggplot(~DHARMa::testDispersion(cm))

    return(plot2) 
  }   

And got this error message:

Error in plot(cm_simres, asFactor = FALSE) : object 'cm_simres' not found

NOTE:

  • cm is a model
  • It showed the correct output in cm_simres when I rand the function with some lm() and "glm()
  • when I removed ~ from plot1, I got this error: Error in UseMethod("as.grob") :
    no applicable method for 'as.grob' applied to an object of class "NULL"

I opened this issue because it is probably a ggplotfy problem, I tried to run fix() to find bugs, but It was tricky.

Thanks in advance for any help.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions