简体   繁体   English

如何在R中拟合具有两个主成分的线性回归模型?

[英]How to fit a linear regression model with two principal components in R?

Let's say I have a data matrix d 假设我有一个数据矩阵d

pc = prcomp(d)

# pc1 and pc2 are the principal components  
pc1 = pc$rotation[,1] 
pc2 = pc$rotation[,2]

Then this should fit the linear regression model right? 那么这应该适合线性回归模型吗?

r = lm(y ~ pc1+pc2)

But then I get this error : 但后来我得到了这个错误:

Errormodel.frame.default(formula = y ~ pc1+pc2, drop.unused.levels = TRUE) : 
   unequal dimensions('pc1')

I guess there a packages out there who do this automatically, but this should work too? 我想那里有一个自动执行此操作的软件包,但这也应该有用吗?

Answer: you don't want pc$rotation, it's the rotation matrix and not the matrix of rotated values (scores). 答:你不想要pc $旋转,它是旋转矩阵,而不是旋转值矩阵(分数)。

Make up some data: 补充一些数据:

x1 = runif(100)
x2 = runif(100)
y = rnorm(2+3*x1+4*x2)
d = cbind(x1,x2)

pc = prcomp(d)
dim(pc$rotation)
## [1] 2 2

Oops. 哎呀。 The "x" component is what we want. “x”组件就是我们想要的。 From ?prcomp: 来自?prcomp:

x: if 'retx' is true the value of the rotated data (the centred (and scaled if requested) data multiplied by the 'rotation' matrix) is returned. x:如果'retx'为真,则返回旋转数据的值(居中(和缩放,如果请求)数据乘以'旋转'矩阵)。

dim(pc$x)
## [1] 100   2
lm(y~pc$x[,1]+pc$x[,2])
## 
## Call:
## lm(formula = y ~ pc$x[, 1] + pc$x[, 2])

## Coefficients:
## (Intercept)    pc$x[, 1]    pc$x[, 2]  
##     0.04942      0.14272     -0.13557  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM