Power regression in R similar to excel

后端 未结 3 1153
天涯浪人
天涯浪人 2020-12-14 12:05

I have a simple dataset and I am trying to use the power trend to best fit the data. The sample data is very small and is as follows:

structure(list(Discharg         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-14 12:42

    Use nls (nonlinear least squares) as your smoother

    eg

    ggplot(DD,aes(x = Discharge,y = Age)) +
      geom_point() + 
      stat_smooth(method = 'nls', formula = 'y~a*x^b', start = list(a = 1,b=1),se=FALSE)
    

    Noting Doug Bates comments on R-squared values and non-linear models here, you could use the ideas in Adding Regression Line Equation and R2 on graph

    to append the regression line equation

    # note that you have to give it sensible starting values
    # and I haven't worked out why the values passed to geom_smooth work!
    power_eqn = function(df, start = list(a =300,b=1)){
      m = nls(Discharge ~ a*Age^b, start = start, data = df);
      eq <- substitute(italic(y) == a  ~italic(x)^b, 
                   list(a = format(coef(m)[1], digits = 2), 
                        b = format(coef(m)[2], digits = 2)))
      as.character(as.expression(eq));                 
    }
    
    ggplot(DD,aes(x = Discharge,y = Age)) +
      geom_point() + 
      stat_smooth(method = 'nls', formula = 'y~a*x^b', start = list(a = 1,b=1),se=FALSE) +  
      geom_text(x = 600, y = 1, label = power_eqn(DD), parse = TRUE)
    

提交回复
热议问题