Skip to content

Read from data frame, and not from global environment

3 messages · Jochen Einbeck, Brian Ripley

#
Dear members,

assume given  a function of type

test<-function(formula,  data , w){
  ......
  glm1<-glm(formula,  family=poisson, data=data, weights=w)
  ......
}

and a simple example data frame as

test.frame<-data.frame(x=1:10,y=(1:10)*2,a=(1:10)^3).

Let us now execute

test(y ~ x, test.frame, a )

My question is: What do I have to insert at the first occurance of ..... 
in the test function to ensure that

1) 'a'  is read from the data frame (and is only read from the global 
environment if  and only if  'a' is not found in the data frame)
2) glm finds w in in the local environment of the function 'test'

The question is obviously related to  Fernando's problem with   
'Defining a "local" function'  some months ago, though the discussion 
there does not solve the questions above.

Cheers,

Jochen Einbeck
NUI Galway, Ireland
#
I don't think that is the best way to do what I guess you intended. Try 
something like

test <- function(formula,  data , weights)
{
     Call <- match.call()
     Call[[1]] <- as.name("glm")
     Call$family <- quote(poisson)
     glm1 <- eval.parent(Call)
     ....
}

which is probably giving the scoping that you want.

You could do what you ask for at 1) by something like

     wname <- deparse(substitute(w))
     w <- if(wname %in% names(data)) data[[wname]] else get(wname, .GlobalEnv)

and for 2) by replacing .GlobalEnv by an expression constructed by calls 
to environment() (I don't know exactly what you intended here).
On Tue, 2 Aug 2005, Jochen Einbeck wrote:

            
That contradicts 1)!

  
    
1 day later
#
Thanks. It is now working as I wanted, if I use (simplified)

test<-function(formula, data, w){
  wname <- deparse(substitute(w))
  w <- if(wname %in% names(data)) data[[wname]] else get(wname, .GlobalEnv)
  data$w<-w
  glm1<-glm(formula=formula,data=data, weights=w)
  .....
}


What I was looking for in  2) was a more elegant way  (than setting 
data$w<-w)  to make  w  available to the glm function.
Prof Brian Ripley wrote: