[R] Subscripting specified variables in a function

Bill.Venables at csiro.au Bill.Venables at csiro.au
Wed Jun 27 01:25:07 CEST 2007


I think what you are trying to do is quite tricky.  Here is one way you
might like to think about.

> tdat <- data.frame(a = 1:5, b = c(1:3, 101,101))
> tdat
  a   b
1 1   1
2 2   2
3 3   3
4 4 101
5 5 101
> test.fx <- function(dta, expvar, expval) {
  lang <- substitute(subset(dat, v1 > v2),
  	list(dat = substitute(dta), 
		v1 = substitute(expvar), 
		v2 = substitute(expval)))
  newdta <- eval.parent(lang)
  summary(newdta[deparse(substitute(expvar))])
 }
> test.fx(tdat, b, 100)
       b      
 Min.   :101  
 1st Qu.:101  
 Median :101  
 Mean   :101  
 3rd Qu.:101  
 Max.   :101  
> test.fx(tdat, b, 2)
       b         
 Min.   :  3.00  
 1st Qu.: 52.00  
 Median :101.00  
 Mean   : 68.33  
 3rd Qu.:101.00  
 Max.   :101.00  
>  


Bill Venables
CSIRO Laboratories
PO Box 120, Cleveland, 4163
AUSTRALIA
Office Phone (email preferred): +61 7 3826 7251
Fax (if absolutely necessary):  +61 7 3826 7304
Mobile:                         +61 4 8819 4402
Home Phone:                     +61 7 3286 7700
mailto:Bill.Venables at csiro.au
http://www.cmis.csiro.au/bill.venables/ 

-----Original Message-----
From: r-help-bounces at stat.math.ethz.ch
[mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Zodet, Marc W.
(AHRQ)
Sent: Wednesday, 27 June 2007 12:43 AM
To: r-help at stat.math.ethz.ch
Subject: [R] Subscripting specified variables in a function

I'm trying to create a function which will allow me to subset a data set
based on values of various specified variables.  I also want to then
apply some other function(s) (e.g., summary).

 

This is what I've tried so far....

 

> test.fx <- function(dta, expvar, expval) {

+ newdta <- subset(dta, eval(expvar)>expval)

+ summary(newdta$eval(expvar))

+ }

> 

> test.fx(fyc04s, quote(totexp04), 100)

Error in summary(newdta$eval(expvar)) : attempt to apply non-function

> 

 

The subset works fine, but the my attempt to access the specified
variable bombs.  

 

Is there a syntactical change I can make?

Is it better to attach newdta?

 

Thanks in advance for any guidance.

 

Marc

 

Marc W. Zodet, MS                           

Senior Health Statistician

Agency for Healthcare Research and Quality

Center for Financing, Access, and Cost Trends

301-427-1563 (Telephone)

301-427-1276 (Fax)

marc.zodet at ahrq.hhs.gov

 


	[[alternative HTML version deleted]]

______________________________________________
R-help at stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list