gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:02:28 26 4
gpt4 key购买 nike

假设我有一个数据矩阵 d

pc = prcomp(d)

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

那么这应该适合线性回归模型吧?
r = lm(y ~ pc1+pc2)

但是后来我收到了这个错误:
Errormodel.frame.default(formula = y ~ pc1+pc2, drop.unused.levels = TRUE) : 
unequal dimensions('pc1')

我想有一个软件包可以自动执行此操作,但这也应该有效吗?

最佳答案

答:您不想要 pc$rotation,它是旋转矩阵,而不是旋转值(分数)的矩阵。

整理一些数据:

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

哎呀。 “x”组件就是我们想要的。从?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.


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

关于r - 如何在R中拟合具有两个主成分的线性回归模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1805149/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com