how to create many linear models at once and put the coefficients into a new matrix?

后端 未结 2 1443
闹比i
闹比i 2021-01-17 02:10

I have 365 columns. In each column I have 60 values. I need to know the rate of change over time for each column (slope or linear coefficient). I created a generic column as

2条回答
  •  天命终不由人
    2021-01-17 02:48

    Here's a way to do it:

    # Fake data
    dat = data.frame(x=1:60, y1=rnorm(60), y2=rnorm(60), 
                     y3=rnorm(60))
    
    t(sapply(names(dat)[-1], function(var){
       coef(lm(dat[,var] ~ x, data=dat))
    }))
    
       (Intercept)            x
    y1  0.10858554 -0.004235449
    y2 -0.02766542  0.005364577
    y3  0.20283168 -0.008160786
    

    Now, where's that turpentine soap?

提交回复
热议问题