[R] question on function argument

Peter Dalgaard p.dalgaard at biostat.ku.dk
Mon Oct 11 14:03:20 CEST 2004


Edwin Leuven <e.leuven at uva.nl> writes:

> dear all,
> 
> i've looked at the r-intro (chapter 10, writing your own functions)
> and searched the r-help archives but am still stuck at the following.
> 
> i have a simple function, something like:
> 
> myhist<-function(yvar) {
>   y<-subset(myframe,yvar>1 & yvar<=150000,select=yvar)
>   attach(y)
>   hist(yvar)
> }
> 
> 
> calling it as follows:
> 
> myhist(x1)
> 
> gives the following error:
> 
> Error in attach(y) : attempt to set an attribute on NULL
> 
> 
> 
> what am i doing wrong here?

(1) Insufficient information in problem report (what is "myframe"?)

Assuming that myframe is a data.frame containing a variable called
"x1":

(2) Believing that function calls are macros and
(3) Not noticing that subset() has nonstandard argument handling

The construct y<-subset(myframe,yvar>1 & yvar<=150000,select=yvar)
looks inside "myframe" for a variable called "yvar". If there is no
"yvar" in the data frame, then it will search the calling environment,
which might be OK for the "subset" argument, but will almost surely go
wrong for "select". (Read the source for subset.data.frame for the
full story.)

I think that what you thought you were doing is more like

eval(substitute({
   y<-subset(myframe,yvar>1 & yvar<=150000,select=yvar)
   attach(y)
   hist(yvar)
}), list(yvar=quote(x1)))

or maybe

 myhist<-function(yvar) eval.parent(substitute({
   y<-subset(myframe,yvar>1 & yvar<=150000,select=yvar)
   attach(y)
   hist(yvar)
 }))

In either case, you'd probably want a detach() in there as well.

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