[R] passing arguments to subset from a function

David Winsemius dwinsemius at comcast.net
Wed Dec 17 20:25:33 CET 2008


Available free for the typing are the functions for the default and  
the dataframe methods of subset:

 >  subset.default
function (x, subset, ...)
{
     if (!is.logical(subset))
         stop("'subset' must be logical")
     x[subset & !is.na(subset)]
}


 > subset.data.frame
function (x, subset, select, drop = FALSE, ...)
{
     if (missing(subset))
         r <- TRUE
     else {
         e <- substitute(subset)
         r <- eval(e, x, parent.frame())
         if (!is.logical(r))
             stop("'subset' must evaluate to logical")
         r <- r & !is.na(r)
     }
     if (missing(select))
         vars <- TRUE
     else {
         nl <- as.list(1:ncol(x))
         names(nl) <- names(x)
         vars <- eval(substitute(select), nl, parent.frame())
     }
     x[r, vars, drop = drop]
}

(There is also a matrix method.)

-- 
David Winsemius


On Dec 17, 2008, at 2:07 PM, 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.



More information about the R-help mailing list