Skip to content
Prev 8322 / 12125 Next

[R-pkg-devel] Strange behaviour of function called from within a function

Dear John,

This is a scoping issue due to how model formulas are evaluated by nls() 
and other modeling functions. Try this:

tw2 <- function(formula, data, start, control, trace, weights) {
   firstcoef <- c(b1=199, b2=50, b3=0.3)
   cat("firstcoef:\n")
   print(firstcoef)
   cat("weights:"); print(weights)
   data$weights <- weights
   secondw<-nls(formula, data, firstcoef, control, algorithm=NULL, TRUE, 
weights=weights)
   secondw
}

 > tw2(hobbsu, weeddf, st2, control=list(), trace=TRUE, weights=wts)
firstcoef:
    b1    b2    b3
199.0  50.0   0.3
weights: [1] 0.5000000000 0.2500000000 0.1250000000 0.0625000000 
0.0312500000 0.0156250000
  [7] 0.0078125000 0.0039062500 0.0019531250 0.0009765625 0.0004882812 
0.0002441406
0.3342481   (3.98e+00): par = (199 50 0.3)
0.01987378  (1.14e-01): par = (199.2897 50.14155 0.3139337)
0.01961683  (2.88e-04): par = (199.8481 50.2582 0.3133964)
0.01961683  (1.97e-06): par = (199.8595 50.26061 0.3133932)
Nonlinear regression model
   model: weed ~ b1/(1 + b2 * exp(-b3 * tt))
    data: data
       b1       b2       b3
199.8595  50.2606   0.3134
  weighted residual sum-of-squares: 0.01962

Number of iterations to convergence: 3
Achieved convergence tolerance: 1.975e-06

(Your second attempt worked because you stuck the variable weights in 
the global environment.)

I hope that this does what you want.

John
On 2022-08-12 6:40 p.m., J C Nash wrote: