【发布时间】:2019-06-28 17:22:49
【问题描述】:
我想在 R 中在不明确知道之前的预测变量数量的情况下进行多因素线性回归。
我有大约 400 个数组,我正在通过一个循环执行每个数组的多因子回归。
对于每个回归,我最多有 7 个预测变量。
我的问题在于'最多',某些数组不存在某些预测变量。
在这种情况下,当我做这样的事情时,它显然是行不通的
LinearModel = lm(Y ~ V1 + V2 + V3 + V4 + V5 + V6 + V7, data = foo)。
其中 foo 是一个有 8 列的数据框 [Y, V1, V2, ... V7]
我实际上找到了一个解决方案,其中包括用零向量替换任何丢失的预测器。 它可以工作,但我不得不保留和处理许多占用内存的无用数据(每个数组都有大约 40,000 个值)。
这是代码的样子
for (current_array in arrays)
{
Y = get.data(current_array) #Actually lot of long process
regressors_mat = matrix (0, nrow = 40000, ncol = 7) # All non existing indicators will stay at 0
colmatreg = 0
for (predictor in predictors)
{
colmatreg = colmatreg + 1
if (!(predictor.exists.for(current_array))
{
next
}
regressors_mat[, colmatreg] = get.data(predictor) #Actually lot of long process
}
dtf = data.frame(cbind(regressors_mat, Y))
colnames(dtf)[ncol(dtf)] = "Y"
LinearModel = lm(Y ~ V1 + V2 + V3 + V4 + V5 + V6 + V7, data = dtf)#won't work if the 7 predictors are not available
# Long process
}
# Long process
是否有执行多因素线性回归而无需编写 LinearModel = lm(Y ~ V1 + V2 + V3 + V4 + V5 + V6 + V7, data = dtf) 当所有 7 个预测变量都不可用且 无需保存和处理 40,000 x 400 x nb_of_unavailable_predictors ?
这样的东西会很棒:
for (current_array in arrays)
{
Y = get.data(current_array)
nbcol = nb.predictos.available(current_array) # I can have this function
regressors_mat = matrix (0, nrow = 40000, ncol = nbcol )
colmatreg = 0
for (predictor in predictors)
{
colmatreg = colmatreg + 1
if (!(predictor.exists.for(current_array))
{
next
}
regressors_mat[, colmatreg] = get.data(predictor) #Actually lot of long process
}
dtf = data.frame(cbind(regressors_mat, Y))
colnames(dtf)[ncol(dtf)] = "Y"
LinearModel = lm(Y ~ colSums(dtf[, 1:(ncol(dtf) -1)], data = dtf)
#Allowing to make the multifactorial model without knowing in advance the number of factors
}
或者如果它更有效,我什至不必预先分配,我可以连接列
任何帮助或建议都会很棒。谢谢!
【问题讨论】:
标签: r linear-regression