[R] problems sourcing in vs interactive

Peter Dalgaard BSA p.dalgaard at pubhealth.ku.dk
Mon Feb 19 15:54:52 CET 2001


Bill Simpson <wsi at gcal.ac.uk> writes:

> If I source in the function (see below) calib(), I get:
> > source("papers/helle/threshold.r")
> > calib()
> Error in eval(expr, envir, enclos) : Object "energy" not found
> 
> But if I cut and paste the code for calib() one line at a time into the R
> window it works fine.
> 
> calib<-function()
> {
> contrast<-c(.01,.02,.0325,.055,.0775,.1,.125,.15,.175,.2)
> energy<-c(3.53189e-5,.000141275,.000373056,.0010684,.00212134,.00353189,
> .00551857,.00794675,.0108164,.0141275)
> plot(contrast,energy)
> fit<-nls(energy~a*contrast^2,start=list(a=.01))
> contrastfit<-seq(min(contrast),max(contrast),length=40)
> energyfit<-coef(fit)[[1]]*contrastfit^2
> lines(spline(contrastfit,energyfit))
> list(summary(fit))
> #for these data, energy=.3532 * contrast^2 s deg^s
> }
> 
> What is wrong and how to fix? The problem seems to originate in nls()
> since the plot is produced OK: plot() can find the object "energy". I
> think I have the nls() syntax right.

That's a problem with functions vs. command line entry, source() never
gets into it.  It's the usual problem where a routine gets confused
about where it should get its variables from. Easiest way is to add an
explicit data= argument to the nls call:

fit<-nls(energy~a*contrast^2,start=list(a=.01),
   data=data.frame(contrast,energy))

[Surely you realize that that model is not really nonlinear at all?]

The default value for data= in nls() is list(), which gets in trouble
with

    varIndex <- sapply(varNames, function(varName, data, respLength) {
        length(eval(as.name(varName), data))%%respLength == 0
    }, data, length(eval(formula[[2]], data)))

since the eval(..., data) constructs will look in the list, then in
the *current* environment.

Defaulting to data=environment(formula) looks like it might work
better. Or maybe one should have eval(..., data, parent.frame()).

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list