2017-04-09 134 views
0

我试图拟合一个非线性模型,其中有近似50个变量(因为有一年固定效应)。问题是我有不能写入完整的公式向下像R中具有许多自变量(固定效应)的非线性模型

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. gnls函数试图factor(year)简化,但它不工作。
  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的起始值?

+0

如果你提供了一个[可重现的例子](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)与样本输入数据,它会更容易帮助所以我们实际上可以运行代码并测试可能的解决方案。 – MrFlick

回答

4

既然你没有提供任何数据。例如,我写我自己 - 这是完全没有意义和模型实际上不起作用,因为它也有坏的数据覆盖,但它跨越得到点:

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命令来构建您正在尝试执行的操作非常简单。

+0

非常感谢!这真的很有帮助! –

+0

考虑'?reconulate' ... –