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

╄→гoц情女王★ 提交于 2020-01-11 07:51:44

问题


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 a series of numbers from 1:60 to represent the 60 corresponding time intervals. I want to create 356 linear regression models using the generic time stamp column with each of the 365 columns of data.

In other words, I have many columns and I would like to create many linear regression models at once, extract the coefficients and put those coefficients into a new matrix.


回答1:


First of all, statistically this might not be the best possible approach to analyse temporal data. Although, regarding the approach you propose, it is very simple to build a loop to obtain this:

Coefs <- matrix(,ncol(Data),2)#Assuming your generic 1:60 column is not in the same object
for(i in 1:ncol(Data)){
Coefs[i,] <- lm(Data[,i]~GenericColumn)$coefficients
} 



回答2:


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?



来源:https://stackoverflow.com/questions/26922815/how-to-create-many-linear-models-at-once-and-put-the-coefficients-into-a-new-mat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!