Search code examples
raggregateaggregate-functionshavinghaving-clause

How can I access columns by name in an anonymous data frame object for filtering in R?


I've got this one-liner:

aggregate(. ~ gear,mtcars[mtcars$mpg>20,c('gear','mpg')],mean)

Now I want to filter by mpg>25 like his:

aggregate(. ~ gear,mtcars[mtcars$mpg>20,c('gear','mpg')],mean)[mpg>25,]

But now I get some 1743 lines of NA entries

any ideas?


Solution

  • Here is another solution with base functions:

    subset(aggregate(. ~ gear,mtcars[mtcars$mpg>20,c('gear','mpg')],mean), mpg>25)
    

    and here is a solution with data.table

    library(data.table)
    M <- data.table(mtcars)
    M[mpg>20, .(mpg=mean(mpg)), by=gear][mpg>25]