Search code examples
rnls

nls.lm : Non-numeric argument to binary operator error but all my args are numeric


I am trying to run a nonlinear least squares regression using minpack.lm:nls.lm. The equation to be minimized is e = x - p1*t1 -p2*t2 - svdep , where t1 and t2 are changed so that the sum of squares of e is minimized.

gnfun <- function(x, p1, p2, t1, t2, svdep){
  x - p1*t1 - p2*t2 - svdep 
}
start <- list(t1=-0.1095389, t2=0.02329868)
gn2 <- nls.lm(par=start, fn=gnfun, x=X1, p1=p1.1, p2=p1.2,      
svdep=Epsvd1)
Error in p1 * t1 : non-numeric argument to binary operator

X1
    X1           X2           X3           X4           X5           X6 
7.725156e-08 7.342344e-08 7.334688e-08 7.572031e-08 7.350000e-08 7.441875e-08 
    X7           X8           X9          X10 
7.388281e-08 7.105000e-08 7.357656e-08 7.028438e-08 

Epsvd1
[1] 3.210028e-05 3.238753e-05 3.160692e-05 3.270296e-05 3.625271e-05 3.167958e-05
[7] 3.667674e-05 3.317648e-05 3.574715e-05 3.335333e-05

p1.1
[1] 0.001156993 0.001159083 0.001158931 0.001162099 0.001160497 0.001158225
[7] 0.001157901 0.001157770 0.001161935 0.001163280

p1.2
[1] 0.005751636 0.005710543 0.005711749 0.005697742 0.005720252 0.005765593
[7] 0.005759443 0.005778480 0.005759381 0.005712900

class(p1.1)
[1] "numeric"

class(p1.2)
[1] "numeric"

> class(X1)
[1] "numeric"

> class(Epsvd1)
[1] "numeric"

I cannot figure out why I got the error 'non-numeric argument to binary operator' for p1*t1, even though p1 and t1 are both numeric .

I would appreciate any advice as to why I am getting this error message, and what I need to do in order to get this to run properly.


Solution

  • You need to remember that you are passing a list and need to pull parameters from that list using [[:

     gnfun <- function(x, p1, p2, par=par, svdep){
                    x - p1*par[[1]] - p2*par[[2]] - svdep 
              }
     start <- list(t1=-0.1095389, t2=0.02329868)
     gn2 <- nls.lm(par=start, fn=gnfun, x=X1, p1=p1.1, p2=p1.2,      
                   svdep=Epsvd1)
     summary(gn2)
    
    Parameters:
        Estimate Std. Error t value Pr(>|t|)
    t1  0.003322   0.092779   0.036    0.972
    t2 -0.006510   0.018755  -0.347    0.737
    
    Residual standard error: 2.019e-06 on 8 degrees of freedom
    Number of iterations to termination: 2 
    Reason for termination: Relative error in the sum of squares is at most `ftol'.