Anthony Damico
Anthony Damico

Reputation: 6124

how to pass an expression through a function for the subset function to evaluate in R

i'm trying to write a subset method for a different object class that i'd like users to be able to execute the same way they use the subset.data.frame function. i've read a few related articles like this and this, but i don't think they're the solution here. i believe i'm using the wrong environment, but i don't understand enough about environments and also the substitute function to figure out why the first half of this code works but the second half doesn't. could anyone explain what i'm doing wrong below and then how to make a working lsubset function that could take gear == 4 as its second parameter? sorry if my searches missed a similar question.. thanks!!

# create a list of mtcars data frames
mtlist <- list( mtcars , mtcars , mtcars )
# subset them all - this works
lapply( mtlist , subset , gear == 4 )


# create a function that simply replicates the task above
lsubset <- 
    function( x , sset ){
        lapply( x , subset , sset )
    }

# this does not work for some reason
lsubset( mtlist , gear == 4 )

Upvotes: 1

Views: 288

Answers (1)

Tyler Rinker
Tyler Rinker

Reputation: 110054

What about:

lsubset <- 
    function( x , ... ){
        lapply( x , subset , ... )
    }

lsubset( mtlist , gear == 4 )

Upvotes: 5

Related Questions