[R] [R/S] strange

Peter Dalgaard p.dalgaard at biostat.ku.dk
Wed Sep 1 23:24:23 CEST 2004


Erin Hodgess <hodgess at gator.uhd.edu> writes:

> Dear R and S People:
> 
> I have run across something very strange.  Here is a function that I wrote
> for R:
> 
> boot1 <- function(y,method="f",p=1) {
>   n1 <- length(y)
>   n2 <- n1*p
>   n3 <- n2 - 1
>   a <- 0.5*(outer(1:n3,1:n3,function(x,y){n2 - pmax(x,y)}))
>   return(a)
> }
[and it doesn't work in S]

Well, if you didn't understand what lexical scoping was about before,
now is your chance... 

n2 is in the lexical scope of the (unnamed) function that is getting
passed to outer(), because the function is defined in (the environment
of) the call to boot1. Therefor the value of n2 is available inside
that function.

S doesn't have lexical scoping. Instead it has "frame 0" and "frame
1", which can be used as "scratchpads" for routines to scribble pieces
of information on. So a not-quite-so-dirty variant of your solution is
to assign n2 to frame 1, rather than as permanent data. Not the only
solution, obviously.

-- 
   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




More information about the R-help mailing list