r - R 中的非线性最小化 (nlm) 错误 : incorrect number of dimensions

标签 r optimization nlm

我有这段代码,它计算负二项式分布, 带参数:

ce <- c(0, 1, 2, 3, 4, 5)
ce <- as.integer(ce)
comp <- c(257, 155, 64, 17, 5, 2)
comp <- as.integer(comp)
data.cells <- data.frame(ce, comp)

params <- c(5, 1.5) # vector of 2 params, x and κ. 
dat <- data.cells

函数:

negbinll <- function(dat,params) {
  if (missing(dat)||missing(params)) {
    print('Plese add values for the model')
  } else if (params[1]<0||params[2]<0) {
    print('Plese make sure your parameters are >0')
  } else {
    p <- params[1]/(params[1]+params[2])
    N <- params[1] + dat[,1] - 1
    log.l <- sum(dat[2]*dnbinom(dat[,1], size = N, prob = p, log = TRUE))
    return(log.l)
  }
}

现在,这段代码的结果是

> negbinll(dat, params)
[1] -591.024

下一步是使用nlm(非线性最小化)来找到 x 和 κ 的最大似然估计,假设 params = (x, κ)

nlm(negbinll, dat, p = params)
Error in dat[, 1] : incorrect number of dimensions

但是,如果我将初始函数中的 dat[,1] 更改为 dat[1],则会出现错误: 数学函数的非数字参数

有什么建议吗?谢谢

最佳答案

datparams 值在 negbinll 函数内匹配不正确。要对其进行调试,请将 browser() 放入 negbinll 函数中并调用 nlm 代码行。在 Debug模式下,您可以打印 datparams 的值,并看到它们没有正确匹配。

注意:调试后,从negbinll函数中删除browser()命令

negbinll <- function(dat,params) {
  browser()
  if (missing(dat)||missing(params)) {
    print('Plese add values for the model')
  } else if (params[1]<0||params[2]<0) {
    print('Plese make sure your parameters are >0')
  } else {
    p <- params[1]/(params[1]+params[2])
    N <- params[1] + dat[,1] - 1
    log.l <- sum( dat[2] *dnbinom(dat[,1], size = N, prob = p, log = TRUE))
    return(log.l)
  }
}

Browse[2]> params
# ce comp
# 1  0  257
# 2  1  155
# 3  2   64
# 4  3   17
# 5  4    5
# 6  5    2
Browse[2]> dat
# [1] 5.0 1.5

关于r - R 中的非线性最小化 (nlm) 错误 : incorrect number of dimensions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42335628/

相关文章:

r - 在 DigitalOcean ubuntu 服务器上托管 Shiny 的应用程序时出错

perl - 使用 inline::C 来加速数学是否值得

java - 仅对最新的异步更新数据运行计算

python - PuLP CBC 多线程不适用于 COIN_CMD

r - 优化错误 : function cannot be evaluated at initial parameters

r - stats包中nlm函数的源码

r - 如何从数据框列表中提取键名

r - 在 Shiny 的导航栏中插入链接

r - 如何打造临床环境洁净?

r - nlm起始值的选择问题