【问题标题】:Scoring new data using old factor scores in R使用 R 中的旧因子分数对新数据进行评分
【发布时间】:2018-05-25 16:15:22
【问题描述】:

我在 R 中使用 factanal 将 30 个变量数据集减少到 7 个因子,然后在 lm 模型中使用此过程输出的因子分数(来自 fa$scores)。到目前为止,如此简单......

但是,我使用的自变量与我的依赖变量相比滞后一个时期(因为该模型有望预测未来)。我现在有所有 30 个输入变量,我需要预测下一个周期依赖 var 的值,所以我的问题是这个。如何使用我已经完成的工作的事实输出来计算这 30 个新变量的 7 个因子得分?一旦有了这些,我就可以使用 lm 模型来预测下一个周期。

我在下面使用的代码示例(目标变量在 mydata 的第一列):

#extract factors
fitted_data <- factanal(mydata[,-1],7,rotation="varimax",lower=0.05,scores="regression")

#add factor scores back to main dataset
mydata  <- cbind(mydata,fitted_data$scores)

'#inear regression model to predict my target_variable using factors I've extracted
mod1 <- lm(Target_Var ~ Factor1+ Factor2 + Factor3 + Factor4 + Factor5 + Factor6 + Factor7,data=mydata) 

我在一个名为“new_data”的数据集中有最新的 30 个自变量,我只是想使用已经计算的因子载荷来计算 7 个因子得分,但我一生都无法弄清楚如何计算。 ....

非常感谢任何帮助。

【问题讨论】:

  • 嘿,你能分享一些关于你的数据的东西吗?例如dput(head(mydata)) & dim(mydata) 对复制很有用

标签: r


【解决方案1】:

解决方案在这里:https://stat.ethz.ch/pipermail/r-help/2002-April/020278.html

我在下面测试了它,似乎工作正常:)

# variables, factors, dimension of data
vars <- 5
f <- 2
N <- 10

# function from https://stat.ethz.ch/pipermail/r-help/2002-April/020278.html
newFactors <- function(model_data, new_data, fitted_data){
  coef <- solve(fitted_data$correlation) %*% fitted_data$loadings
  means <- apply(model_data, 2, mean)
  sds <- apply(model_data, 2, sd)
  scale(new_data, means, sds) %*% coef
}

# sample data
mydata <- as.data.frame(do.call(cbind, lapply(1:vars, function(i){
  runif(N)
})))
target_data <- data.frame(y = runif(N))

# extract factors
fitted_data <- factanal(mydata,f,rotation="varimax",lower=0.05,scores="regression")
factor_data <- fitted_data$scores
# check scores with new function
check <- newFactors(mydata, mydata, fitted_data)
max(abs(check-factor_data)) # float issue

# new data sample
N2 <- 3
new_data <-  as.data.frame(do.call(cbind, lapply(1:vars, function(i){
  runif(N2)
})))

# the factor loadings for new data
new_factor_data <- newFactors(mydata, new_data, fitted_data)

【讨论】:

  • 效果很好。非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-02
  • 2013-03-23
  • 2016-02-14
  • 2022-01-12
  • 1970-01-01
  • 1970-01-01
  • 2019-04-13
相关资源
最近更新 更多