y <- matrix(c(1,2,3,4,5,6,7,8,9),3,3)
p <- 3
oldgamma <- as.matrix(rep(1,3))
func1 <- function(i, j, y, oldgamma) {
return(y[i,j]/(oldgamma[i] + oldgamma[j]))
}
func1 <- Vectorize(func1)
outer(1:p, 1:p, func1, y, oldgamma)
它返回错误消息: y [i,j]出错:维数不正确
有人可以帮我解决这个问题吗?
答案 0 :(得分:0)
可能有帮助
y/(oldgamma[row(y)]+oldgamma[col(y)])
# [,1] [,2] [,3]
#[1,] 0.5 2.0 3.5
#[2,] 1.0 2.5 4.0
#[3,] 1.5 3.0 4.5
或者
y/with(expand.grid(rep(list(1:p),2)),
oldgamma[Var1]+oldgamma[Var2])
或使用您的代码
func1 <- function(i, j, y, oldgamma) {
return(y[cbind(i,j)]/(oldgamma[i] + oldgamma[j]))
}
outer(1:p, 1:p, func1, y, oldgamma)
# [,1] [,2] [,3]
#[1,] 0.5 2.0 3.5
#[2,] 1.0 2.5 4.0
#[3,] 1.5 3.0 4.5