此代码不起作用:
library(multipol)
xyz <- function(px,py,pz,coef){
A <- array(0, c(px+1,py+1,pz+1))
P <- as.multipol(A)
P[px,py,pz] <- coef
P
}
> xyz(1,0,0,1)
Error in eval(expr, p) : objet 'px' introuvable
显示回溯:
7.
eval(expr, p)
6.
eval(expr, p)
5.
eval.parent(ii, 3)
4.
.handleTheOffset(mc, dim, offset, dn)
3.
`[<-.multipol`(`*tmp*`, px, py, pz, value = 1)
2.
`[<-`(`*tmp*`, px, py, pz, value = 1)
1.
xyz(1, 0, 0, 1)
我找到了解决方法:
xyz <- function(px,py,pz,coef){
A <- array(0, c(px+1,py+1,pz+1))
P <- as.multipol(A)
f <- function(){
P[px,py,pz] <- coef
P
}
f()
}
> xyz(1,0,0,1)
, , z^0
y^0
x^0 0
x^1 1
好吗?嗯,等等。现在,我在一个程序包中有此功能:
representation <- function(P){
monomials <- which(P!=0, arr.ind = TRUE) - 1
kmax <- max(rowSums(monomials))
allDegrees <- degreesTable(kmax)
degrees <- row.match(as.data.frame(monomials), allDegrees)
coefficients <- apply(monomials, 1, function(ijk){
f <- function() P[ijk[1],ijk[2],ijk[3]]
f()
})
list(degrees=degrees, coefficients=coefficients)
}
> representation(P)
Error in eval(mc) : objet 'ijk' introuvable
但是,当技巧不在函数内部时,它就起作用了。这有效:
coefficients <- apply(monomials, 1, function(ijk){
f <- function() P[ijk[1],ijk[2],ijk[3]]
f()
})
回溯:
8.
eval(mc)
7.
eval(mc)
6.
`[.multipol`(P, ijk[1], ijk[2], ijk[3]) at representation.R#38
5.
P[ijk[1], ijk[2], ijk[3]] at representation.R#38
4.
f() at representation.R#39
3.
FUN(newX[, i], ...)
2.
apply(monomials, 1, function(ijk) {
f <- function() P[ijk[1], ijk[2], ijk[3]]
f()
}) at representation.R#37
1.
representation(P)
我该怎么办?有招吗我不太了解使用eval.parent
的代码。
我找到了解决方法:
coefficients <- apply(monomials, 1, function(ijk){
ijk <<- ijk
P[ijk[1],ijk[2],ijk[3]]
})
我仍然对更好的解决方案和解释感兴趣。
更容易:
coefficients <- c(P[monomials])
但是我仍然很感兴趣...