简体   繁体   中英

Nonlinear model with many independent variables (fixed effects) in R

I'm trying to fit a nonlinear model with nearly 50 variables (since there are year fixed effects). The problem is I have so many variables that I cannot write the complete formula down like

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))

where y is the binary response variable, year.matirx is a matrix of 45 columns (indicating 45 different years) and x is the independent variable. The parameters need to be estimated are t1, t2, ..., t45, g, d .

I have good starting values for t1, ..., t45, g, d . But I don't want to write a long formula for this nonlinear regression.

I know that if the model is linear, the expression can be simplified using

l_model = lm(y ~ factor(year) + ...)
  1. I tried factor(year) in gnls function but it does not work.
  2. Besides, I also tried

    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))

It also returns me error message.

So, is there any easy way to write down the nonlinear formula and the starting values in R ?

Since you have not provided any example data, I wrote my own - it is completely meaningless and the model actually doesn't work because it has bad data coverage but it gets the point across:

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)

This may not be the most efficient way to do it, but since you can pass a string to as.formula it's pretty easy to use paste commands to construct what you are trying to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM