[R] environment problems

Matias Salibian-Barrera msalibian at yahoo.ca
Tue Aug 19 21:21:45 CEST 2008


Hello,

I realize this is not a new problem, but I'm hoping somebody can point me in the right direction. 

The function silly() below calls gam() (from package gam) with different values of the span parameter for lo(), which is used inside the formula of gam. The values for span are stored in a vector that resides in the function silly(), and that lo(), for some reason, needs to see.

A hack to get around this is provided in silly2(), where the current value for span is forcefully assigned to a variable in the "top" environment, that is always visible (I believe?) Of course, this is not good programming practice (to say the least).

I'd very much appreciate it if somebody could help me find a better way to make silly() work.

Thanks a lot in advance.

Matias

-----------------------------
> version
               _                           
platform       i386-redhat-linux-gnu       
arch           i386                        
os             linux-gnu                   
system         i386, linux-gnu             
status                                     
major          2                           
minor          7.1                         
year           2008                        
month          06                          
day            23                          
svn rev        45970                       
language       R                           
version.string R version 2.7.1 (2008-06-23)
> 
> silly <- function(x, y, alphas = seq(.1, .9, length=9)) {
+ a <- rep(0, 9)
+ for(i in 1:9) {
+ a[i] <- predict(gam(y~lo(x, span = alphas[i]), family=poisson), type='response')[23]
+ }
+ return(a)
+ }
> 
> silly2 <- function(x, y, alphas = seq(.1, .9, length=9)) {
+ a <- rep(0, 9)
+ for(i in 1:9) {
+ assign("tt", alphas[i], envir=.GlobalEnv)
+ a[i] <- predict(gam(y~lo(x, span = tt), family=poisson), type='response')[23]
+ }
+ return(a)
+ }
> 
> library(gam)
Loading required package: splines
> set.seed(321)
> x <- runif(50)
> y <- rpois(50, lambda=10)
> silly(x=x,y=y)
Error in lodummy(span = alphas[i]) : object "alphas" not found
> silly2(x=x,y=y)
[1] 11.56997 10.98681 10.73250 10.63455 10.62692 10.61285 10.61779 10.63234
[9] 10.66311
> 
> 


      __________________________________________________________________
[[elided Yahoo spam]]



More information about the R-help mailing list