Getting the y-axis intercept and slope from a linear regression of multiple data and passing the intercept and slope values to a data frame

后端 未结 1 1615
误落风尘
误落风尘 2020-12-21 00:26

I have a data frame x1, which was generated with the following piece of code,

x <- c(1:10)
y <- x^3
z <- y-20
s <- z/3
t <- s*6
q         


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

    I suppose you're looking for geom_smooth. If you call this function with the argument method = "lm", it will calculate a linear fit for all groups:

    ggplot(xm, aes(x = x, y = value, color = cols)) +
      geom_point(size = 3) +
      labs(x = "x", y = "y") + 
      geom_smooth(method = "lm", se = FALSE)
    

    enter image description here

    You can also specify a quadratic fit with the poly function and the formula argument:

    ggplot(xm, aes(x = x, y = value, color=cols)) +
      geom_point(size = 3) +
      labs(x = "x", y = "y") + 
      geom_smooth(method = "lm", se = FALSE, formula = y ~ poly(x, 2))
    

    enter image description here


    To extract the corresponding regression coefficients, you can use this approach:

    # create a list of coefficients
    fits <- by(xm[-2], xm$cols, function(i) coef(lm(value ~ x, i)))
    
    # create a data frame
    data.frame(cols = names(fits), do.call(rbind, fits))
    
    #   cols X.Intercept.         x
    # y    y   -277.20000 105.40000
    # s    s    -99.06667  35.13333
    # t    t   -594.40000 210.80000
    

    If you want a quadratic fit, just replace value ~ x with value ~ poly(x, 2).

    0 讨论(0)
提交回复
热议问题