循环累积替换

时间:2014-06-02 13:41:11

标签: r loops for-loop

我是R的新手,并且在我的第一个循环中混乱,所以请耐心等待我。

我有一个如下所示的数据集:

VarName Value
Var1a   1
Var1b   3
Var2a   5
Var2b   4
Var3a   7
Var3b   6
CoeffVar1   0.55
CoeffVar2   0.75
CoeffVar3   -2.15

它包含变量和系数。我想将系数应用于这些变量,并将“a变量”替换为“b变量”。例如:

Estimation0将使用3“变量”(Var1a,Var2a和Var3a)和零“b变量”。

Estimation0  = Var1a*Coefficient1 + Var2a*Coefficient2 + Var3a*Coefficient3 = -10.75

我想要做的是逐步将Var1-3替换为Var1-3b并保存每个估算。在这种情况下:

Estimation1 = Var1b*Coefficient1 + Var2a*Coefficient2 + Var3a*Coefficient3 = -9.65
Estimation2 = Var1b*Coefficient1 + Var2b*Coefficient2 + Var3a*Coefficient3 = -10.4
Estimation3 = Var1b*Coefficient1 + Var2b*Coefficient2 + Var3b*Coefficient3 = -8.25

你知道怎么办?

我有点失落所以非常感谢任何建议!

1 个答案:

答案 0 :(得分:2)

DF <- read.table(text="VarName Value
Var1a   1
Var1b   3
Var2a   5
Var2b   4
Var3a   7
Var3b   6
CoeffVar1   0.55
CoeffVar2   0.75
CoeffVar3   -2.15", header=TRUE, stringsAsFactors=FALSE)

#reorganize data
mat <- matrix(DF$Value[1:6], nrow=2)
coef <- DF$Value[7:9]

#all combinations
var <- as.matrix(expand.grid(lapply(seq_len(ncol(mat)), function(j) mat[,j])) )
#      Var1 Var2 Var3
# [1,]    1    5    7
# [2,]    3    5    7
# [3,]    1    4    7
# [4,]    3    4    7
# [5,]    1    5    6
# [6,]    3    5    6
# [7,]    1    4    6
# [8,]    3    4    6

#a bit of matrix algebra
var %*% coef
#        [,1]
# [1,] -10.75
# [2,]  -9.65
# [3,] -11.50
# [4,] -10.40
# [5,]  -8.60
# [6,]  -7.50
# [7,]  -9.35
# [8,]  -8.25