R-beta: ?faq example of scoping

Thomas Lumley (thomas@biostat.washington.edu)
Wed, 6 Aug 1997 11:28:46 -0700 (PDT)


Date: Wed, 6 Aug 1997 11:28:46 -0700 (PDT)
From: Thomas Lumley <thomas@biostat.washington.edu>
To: r-help@stat.math.ethz.ch
Subject: R-beta: ?faq example of scoping
In-Reply-To: <199708060311.PAA14297@stat1.stat.auckland.ac.nz>


The current examples of the scoping rules of R in the faq and in R&R's
JCGS paper are clear but a bit artificial.  The following example may be
of interest as it
a) does something useful in R
b) doesn't work in S
c) was written in S independently by myself and at least three of my
fellow students over the past couple of years, causing literally hours of
confusion on each occasion.

jackknife.lm<-function (lmobj) 
{
        n <- length(resid(lmobj))
        jval <- t(apply(as.matrix(1:n), 1, function(i) coef(update(lmobj, 
                subset = -i))))
        (n - 1)* (n-1) * var(jval)/n
}

In order to make it work in S you need to explicitly pass the linear model
object into the function nested in apply(). If you don't and you are lucky
you will get  
Error: Object "lmobj" not found
If you are unlucky enough to have a linear model called lmobj in your
global environment you will get the wrong answer with no warning. 

This version works in S

jackknife.S.lm<-function (lmobj) 
{
        n <- length(resid(lmobj))
        jval <- t(apply(as.matrix(1:n), 1, function(i,lmobj)
 coef(update(lmobj, subset = -i)),lmobj=lmobj))
        (n - 1)* (n-1) * var(jval)/n
}


Thomas Lumley
------------------------------------------------------+------
Biostatistics		: "Never attribute to malice what  :
Uni of Washington	:  can be adequately explained by  :
Box 357232		:  incompetence" - Hanlon's Razor  :
Seattle WA 98195-7232	:				   :
------------------------------------------------------------

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
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@stat.math.ethz.ch
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=