gpt4 book ai didi

r - R 中的错​​误 : nonconformable arguments. 不正确?

转载 作者:行者123 更新时间:2023-12-04 10:07:39 24 4
gpt4 key购买 nike

这是我的代码:

    #define likelihood function (including an intercept/constant in the function.)
lltobit <- function(b,x,y) {
sigma <- b[3]
y <- as.matrix(y)
x <- as.matrix(x)
vecones <- rep(1,nrow(x))
x <- cbind(vecones,x)
bx <- x %*% b[1:2]
d <- y != 0
llik <- sum(d * ((-1/2)*(log(2*pi) + log(sigma^2) + ((y - bx)/sigma)^2))
+ (1-d) * (log(1 - pnorm(bx/sigma))))
return(-llik)
}

n <- nrow(censored) #define number of variables
y <- censored$y #define y and x for easier use
x1 <- as.matrix(censored$x)
x <- cbind(rep(1,n),x1) #include constant/intercept
bols <- (solve(t(x) %*% x)) %*% (t(x) %*% y) #compute ols estimator (XX) -1 XY
init <- rbind(as.matrix(bols[1:nrow(bols)]),1) #initial values

init

tobit1 <- optim(init, lltobit, x=x, y=y, hessian=TRUE, method="BFGS")

其中删失是我的数据表,包括 200 个(删失)y 值和 200 个 x 值。

一切正常,但是在运行 optim 命令时,出现以下错误:
tobit1 <- optim(init, lltobit, x=x, y=y, hessian=TRUE, method="BFGS")
Error in x %*% b[1:2] : non-conformable arguments

我知道这意味着什么,但是由于 x 是一个 200 x 2 的矩阵,而 b[1:2] 是一个 2 x 1 的向量,那么出了什么问题?我尝试转置两者以及初始值向量,但没有任何效果。谁能帮我?

最佳答案

我今天偶然发现了一个类似的问题(“不一致的参数”错误,即使一切看起来都很好),在我的情况下,解决方案是矩阵乘法的基本规则:即 的数量栏目 矩阵必须与的数量相同行 矩阵 = 我必须在乘法方程中切换顺序。
换句话说,在矩阵乘法中(与普通乘法不同),A %*% BB %*% A 不一样.

关于r - R 中的错​​误 : nonconformable arguments. 不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33237043/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com