【问题标题】:Quick way to print the regression line slope of two vectors打印两个向量的回归线斜率的快速方法
【发布时间】:2019-01-13 13:25:23
【问题描述】:

假设我有以下两个向量:

years <- seq(1991, 2000, by = 1)
height <- c(30, 34, 40, 45, 66, 70, 81, NA, 90, 110)

我现在想执行一个简单的线性回归:

lm(formula = height ~ years)

我只需要回归线的斜率即可获得趋势值。 我有什么快速的方法或函数可以给我的两个向量的回归线斜率?

【问题讨论】:

    标签: r function vector linear-regression


    【解决方案1】:

    你会这样做:

    model <- lm(formula = height ~ years)
    
    model$coefficients[2]
    

    输出:

       years 
    8.857353 
    

    一种不太可读的方式也可以直接执行:

    lm(formula = height ~ years)$coefficients[2]
    

    【讨论】:

      【解决方案2】:

      也许这也是:

      years <- seq(1991, 2000, by = 1)
      height <- c(30, 34, 40, 45, 66, 70, 81, NA, 90, 110)
      df1<-data.frame(Yr=years,Ht=height)
      
          lmfun<-function(df,yname,xname){
            f<-as.formula(paste0(yname,"~",xname))
            lm.fit<-do.call("lm",list(data=quote(df),f))
            coef(lm.fit) 
          }
          lmfun(df1,yname="Ht","Yr")[2] #or [1] depending on the need
      

      输出:

           Yr 
      8.857353 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-24
        • 2020-05-05
        • 1970-01-01
        • 2016-01-22
        相关资源
        最近更新 更多