我的示例的以下修改似乎工作正常(还修复了一些语法拼写错误):
LoadStoreModel
if(is.null(model)) {
model
A = diag(5), # a diagonal square matrix
B = matrix(0, 5, 5) # un upper triangular square matrix
)
attr(model, "p")
"%op%"
mode
} else {
vecParams
"%op%"
mode
}
diag(model$A) %op% vecParams[1:5]
model$B[upper.tri(model$B)] %op% vecParams[5 + (1:(5*(5-1)/2))]
if(mode == "load") {
model
} else {
vecParams
}
}
LoadModelFromVector
StoreModelToVector
> StoreModelToVector(m)
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
> m
> m
$A
[,1] [,2] [,3] [,4] [,5]
[1,] 1 0 0 0 0
[2,] 0 2 0 0 0
[3,] 0 0 3 0 0
[4,] 0 0 0 4 0
[5,] 0 0 0 0 5
$B
[,1] [,2] [,3] [,4] [,5]
[1,] 0 6 7 9 12
[2,] 0 0 8 10 13
[3,] 0 0 0 11 14
[4,] 0 0 0 0 15
[5,] 0 0 0 0 0
attr(,"p")
[1] 15
> StoreModelToVector(m)
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
我也尝试过该行的其他变种被评为“密钥更改” . 这些不起作用:
# evaluation happens locally in the environment of the operator function,
# so the actual objects a and b in the parent environment are not affected:
"%op%"
# not sure why this did not work, but it seems that changes are made on local
# copies of the objects as well.
"%op%"
> StoreModelToVector(m)
[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0