R: nls not picking up additional arguments when used in custom function in geom_smooth

后端 未结 1 594
旧时难觅i
旧时难觅i 2020-12-21 11:43

This is a question that relates to my earlier question geom_smooth with facet_grid and different fitting functions. In that question, I was trying to use a different fitting

相关标签:
1条回答
  • 2020-12-21 12:08

    Here's the solution, which greatly benefited from this post. I don't know why the previous version didn't work, but this seems to work fine.

    # Load library
    library(ggplot2)
    
    # Load data
    data(mtcars)
    
    # Smoothing function with different behaviour depending on the panel
    custom.smooth <- function(formula, data,...){
      smooth.call <- match.call()
    
      if(as.numeric(unique(data$PANEL)) == 6) {
        # Nonlinear regression
        smooth.call[[1]] <- quote(nls)
        # Specify formula
        smooth.call$formula <- as.formula("y ~ a * x ^ b")
        # Add initial parameters
        smooth.call$start <- c(a = 300, b = -0.5)
      }else{
        # Linear regression
        smooth.call[[1]] <- quote(lm)
      }
    
      # Perform fit
      eval.parent(smooth.call)
    }
    
    # Plot data with custom fitting function
    p <- ggplot(mtcars,aes(x = disp, y = mpg)) + geom_point() + facet_grid(gear ~ am)
    p <- p + geom_smooth(method = "custom.smooth", se = FALSE)
    print(p)
    
    0 讨论(0)
提交回复
热议问题