0

我正在尝试拟合具有近50 个变量的非线性模型(因为存在年份固定效应)。问题是我有太多的变量,我无法像这样写下完整的公式

nl_exp = as.formula(y ~ t1*year.matrix[,1] + t2*year.matrix[,2] 
                        +... +t45*year.matirx[,45] + g*(x^d))
nl_model =  gnls(nl_exp, start=list(t=0.5, g=0.01, d=0.1))

其中y是二元响应变量,year.matirx是 45 列(表示 45 个不同年份)的矩阵,x是自变量。需要估计的参数是t1, t2, ..., t45, g, d

我有很好的起始值t1, ..., t45, g, d。但我不想为这个非线性回归写一个长公式。

我知道如果模型是线性的,表达式可以简化为

l_model = lm(y ~ factor(year) + ...)
  1. 我尝试factor(year)gnls功能,但它不起作用。
  2. 另外我也试过

    nl_exp2 = as.formula(y ~ t*year.matrix + g*(x^d))

    nl_model2 = gnls(nl_exp2, start=list(t=rep(0.2, 45), g=0.01, d=0.1))

它还向我返回错误消息。

那么,有什么简单的方法可以写下非线性公式和初始值R吗?

4

1 回答 1

5

由于您没有提供任何示例数据,因此我编写了自己的示例数据——它完全没有意义,而且模型实际上不起作用,因为它的数据覆盖率很差,但它明白了这一点:

y <- 1:100
x <- 1:100
year.matrix <- matrix(runif(4500, 1, 10), ncol = 45)

start.values <- c(rep(0.5, 45), 0.01, 0.1) #you could also use setNames here and do this all in one row but that gets really messy
names(start.values) <- c(paste0("t", 1:45), "g", "d")
start.values <- as.list(start.values)

nl_exp2 <- as.formula(paste0("y ~ ", paste(paste0("t", 1:45, "*year.matrix[,", 1:45, "]"), collapse = " + "), " + g*(x^d)"))

gnls(nl_exp2, start=start.values)

这可能不是最有效的方法,但是由于您可以将字符串传递给as.formula它,因此很容易使用paste命令来构建您正在尝试做的事情。

于 2017-04-09T16:05:59.033 回答