当数据是要估计的参数的函数时,R 中的非线性最小二乘法

nonlinear least squares in R when data are a function of parameters to be estimated

我目前正在从 matlab 迁移到 R,并试图找出我想做的事情是否可行。

我想估计 R 中的非线性模型,其中观测值是美国各州。皱纹是其中一个自变量是县级的州级指数,使用要估计的参数计算,即模型如下所示:

log(Y_s) = log(phi) + log(f(theta, X_cs)) + u_s

其中 Y_s 是州级变量,X_cs 是包含州内变量的县级观察值的向量,f() returns 是标量值为该州计算的指数。

到目前为止,我已经尝试使用 R 的 nls 函数,同时转换传递给函数的数据。从索引的细节中抽象出来,代码的更简单版本如下所示:

library(dplyr)

state <- c("AK", "AK", "CA", "CA", "MA", "MA", "NY", "NY")
Y <- c(3, 3, 5, 5, 6, 6, 4, 4)
X <- c(4, 5, 2, 3, 3, 5, 3, 7)
Sample <- data.frame(state, Y, X)

f <- function(data, theta) {
  output <- data %>%
    group_by(state) %>%
    summarise(index = mean(X**theta),
              Y = mean(Y))
}

model <- nls(Y ~ log(phi) + log(index),
             data = f(Sample, theta),
             start = list(phi = exp(3), theta = 1.052))

这个returns一个错误,告诉我梯度是奇异的。我的猜测是因为 R 看不到参数 theta 应该如何在公式中使用。

有没有办法使用 nls 来做到这一点?我知道我可以定义要手动最小化的标准函数,即 log(Y_s) - log(phi) - log(f(theta, X_cs)),并使用最小化例程来估计参数值。但我想使用 nls 的后估计功能,比如为参数估计设置置信区间。非常感谢任何帮助。

抱歉,我拒绝安装那个巨大的元数据包。因此,我使用基数 R:

state <- c("AK", "AK", "CA", "CA", "MA", "MA", "NY", "NY")
Y <- c(3, 3, 5, 5, 6, 6, 4, 4)
X <- c(4, 5, 2, 3, 3, 5, 3, 7)
Sample <- data.frame(state, Y, X)

f <- function(X, state, theta) {
  ave(X, state, FUN = function(x) mean(x^theta))
}

model <- nls(Y ~ log(phi) + log(f(X, state, theta)),
             data = Sample, weights = 1/ave(X, state, FUN = length),
             start = list(phi = exp(3), theta = 1.052))
summary(model)
#Formula: Y ~ log(phi) + log(f(X, state, theta))
#
#Parameters:
#      Estimate Std. Error t value Pr(>|t|)
#phi   2336.867   4521.510   0.517    0.624
#theta   -2.647      1.632  -1.622    0.156
#
#Residual standard error: 0.7791 on 6 degrees of freedom
#
#Number of iterations to convergence: 11 
#Achieved convergence tolerance: 3.722e-06