在R中使用相同的设计矩阵拟合许多线性模型 [英] Fit many linear models in R with identical design matrices

查看:106
本文介绍了在R中使用相同的设计矩阵拟合许多线性模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于神经成像应用程序,我试图通过R中的最小二乘拟合许多线性模型(对lm的标准调用).想象一下,我有一个设计矩阵X.所有模型中的设计矩阵都相同.拟合的数据(Y)会发生变化,结果所有拟合参数(例如beta,p值,残差等)也会发生变化.

For a neuroimaging application, I'm trying to fit many linear models by least squares in R (standard call to lm). Imagine I have a design matrix X. This design matrix will be the same across all of the models. The data (Y) that is being fit will change, and as a result so will all of the fit parameters (e.g. betas, p-values, residuals, etc).

目前,我只是将其粘贴在for循环中,因此它正在对lm进行数十万次调用.似乎必须有一种更好的方法.

At present, I'm just sticking it in a for loop, so it's doing hundreds of thousands of calls to lm. It seems like there's got to be a better way.

我相信计算量最大的部分是矩阵求逆.看起来这是通过lm.fit中的Fortran调用处理的.

I believe the most computationally expensive piece is the matrix inversion. It looks like this gets handled with a Fortran call in lm.fit.

如果我要手工进行回归,我将进行矩阵求逆,然后将其乘以各种数据集.实际上,当我具有良好的设计矩阵(例如,所有连续值的协变量)时,我已经编写了一个函数来执行此操作.但是,我真的很喜欢lm所做的所有工作,例如适当地重新编码我的因子等,并且lm的输出也非常好.

If I were doing this regression by hand, I'd do the matrix inversion, then just multiply it by the various datasets. In fact, I've coded up a function to do that when I have well-behaved design matrices (e.g. all continuously valued covariates). However, I really like all of the work that lm does, like recoding my factors appropriately, etc, and the output of lm is really nice, too.

反正我也有蛋糕要吃吗?就是说,要获得lm的友好性,但要使用这种能力来有效地计算出具有相同设计矩阵的许多模型?

Is there anyway to have my cake and eat it, too? Namely, to get the friendliness of lm, but use that power to computationally efficiently fit many models with identical design matrices?

推荐答案

lm的帮助页面:

如果响应"是矩阵,则线性模型分别拟合为 矩阵每一列的最小二乘法.

If ‘response’ is a matrix a linear model is fitted separately by least-squares to each column of the matrix.

因此,似乎一种简单的方法是将所有不同的y向量组合到一个矩阵中,并将其作为响应传递给一次对lm的调用.例如:

So it would seem that a simple approach would be to combine all the different y vectors into a matrix and pass that as the response in a single call to lm. For example:

(fit <- lm( cbind(Sepal.Width,Sepal.Length) ~ Petal.Width+Petal.Length+Species, data=iris))
summary(fit)
summary(fit)[2]
coef(summary(fit)[2])
coef(summary(fit))[2]
sapply( summary(fit), function(x) x$r.squared )

这篇关于在R中使用相同的设计矩阵拟合许多线性模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆