[R] passing arguments to subset from a function

baptiste auguie ba208 at exeter.ac.uk
Wed Dec 17 20:45:15 CET 2008


I wrote a dirty hack last time I faced this problem, I'll be curious  
to see what is the proper way of dealing with the scoping and  
evaluation rules.

library(datasets)

myfunction<-function(table, extraction)  {
     table2<-subset(table,extraction)
return(table2)
}


condition1 <- quote(iris$Species=="setosa") # I'm not sure how to  
evaluate within the environment, perhaps you could use with(table,  
subset(table, extraction) ) in your function
condition2 <- bquote(.(condition1)  & iris$Sepal.Width < 3.5) # say,  
if you want to concatenate several conditions together

myfunction(iris, extraction= eval(condition1))
myfunction(iris, extraction= eval(condition2))


Best wishes,

baptiste



On 17 Dec 2008, at 19:07, GOUACHE David wrote:

> Hello R-helpers,
>
> I'm writing a long function in which I manipulate a certain number  
> of datasets. I want the arguments of said function to allow me to  
> adapt the way I do this. Among other things, I want my function to  
> have an argument which I will pass on to subset() somewhere inside  
> my function. Here is a quick and simplified example with the iris  
> dataset.
>
> myfunction<-function(table, extraction)  {
>     table2<-subset(table, extraction)
> return(table2) }
>
> myfunction(iris, extraction= Species=="setosa")
>
>
> ############## end
>
> What I would like is for this function to return exactly the same  
> thing as :
> subset(iris, Species=="setosa")
>
>
> Thanks for your help.
>
> Regards,
>
> David Gouache
>
> ______________________________________________
> R-help at r-project.org 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.

_____________________________

Baptiste Auguié

School of Physics
University of Exeter
Stocker Road,
Exeter, Devon,
EX4 4QL, UK

Phone: +44 1392 264187

http://newton.ex.ac.uk/research/emag



More information about the R-help mailing list