Nonlinear regression with a vectorized variable in R

64 Views Asked by At

I want to find the parameters a and b to fit my data with nlsLM. There are three things that make this more complicated than normal nonlinear regression with nlsLM that I know:

  1. N_l is the vectorized variable and the function should output the maximum value for all possible values of N_l.

  2. The variable m depends on the value of N_l and their relationship is given in dataframe Multi.Presence.

  3. In the term combn(e,k,sum), e is supposed to be the columns e_1,e_2,e_3,e_4,e_5 of the dataframe DATA that the nonlinear regression is being applied to.

I try to use the following:

    func <- function(N_b, N_l,A,x.sqr,e_1,e_2,e_3,e_4,e_5,S,a,b) {
    R <- sapply(seq(N_l), function(k) {max(Multi.Presence$m[k] * ((k/N_b) + 
                (A * combn(e,k,sum) / x.sqr) * (b*S^a)))})
      return(R)
    } 

    regression <- nlsLM(R ~ func(N_b, N_l,A,x.sqr,e_1,e_2,e_3,e_4,e_5,S,a,b), 
             data = DATA, 
             start = c(a = 0.01, b = 0.01))

    summary(regression)

     >dput(DATA)
     structure(list(N_b = c(5, 5, 5, 5, 5), N_l = c(4, 5, 4, 3, 4), 
     A = c(-12, -15, -12, -9, -12), x.sqr = c(1440, 2250, 
     1440, 810, 1440), e_1 = c(21.8, 29, 21.8, 14.6, 21.8), 
     e_2 = c(9.8, 17, 9.8, 2.6, 9.8), e_3 = c(-2.2, 5, -2.2, 
     -9.4, -2.2), e_4 = c(-14.2, -7, -14.2, 0, -14.2), 
     e_5 = c(0, 19, 0, 0, 0), S = c(12, 15, 12, 9, 12), 
     R = c(0.591896859, 0.65922266, 
     0.5562939413, 0.47407075, 0.597435113)), 
     row.names = c(NA, 5L), class = "data.frame")

     > dput(Multi.Presence)
     structure(list(N_l = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), m = c(1.2, 
     1, 0.85, 0.65, 0.65, 0.65, 0.65, 0.65, 0.65, 0.65)), row.names = c(NA, 
     -10L), class = "data.frame")

I am not sure how to address these three issues. How do I keep N_l vectorized? How to include m in dataframe DATA so I can use it in the nlsLM function later. And finally, how to I use the combn function for the 5 e columns e_1,e_2,e_3,e_4,e_5.

Just to show where I started from. before I wanted to do the regression analysis the function R was defined as:

R <- function(x){
  N_b <- x[1]
  N_l <- x[2]
  A <- x[3]
  x.sqr <- x[4]
  S <- x[10]
  e <- x[grepl("e_\\d",names(x))]
  f <- sapply(seq(N_l),function(k) max(Multi.Presence$m[k] * ((k/N_b) + 
                                       (A * combn(e,k,sum) / x.sqr) * S )))
  c(val = max(f), pos = which.max(f))
}

DATA.Proposed <- cbind(DATA, vars = t(apply(DATA, 1, R)))
0

There are 0 best solutions below