Tweet about this on TwitterShare on LinkedInShare on FacebookGoogle+Share on StumbleUponEmail to someone

Quite a handy couple of lines of code to subset a list in R to just those elements which meet a certain condition. Here’s an example to return only those elements of a list which are a certain class.

Thanks to this StackOverflow answer.

list.condition <- sapply(input.list, function(x) class(x)=="desired.class")
output.list  <- input.list[list.condition]

Comments (5)

  1. As I just posted to the StackOverflow thread, this is what the Filter() function was made for. Also, you may want to avoid using `==’ to test for an object’s class. Check out inherits() — much more robust.

    • markbulling

      Thanks for this Jason. I hadn’t come across Filter() (or any other of the higher level functions) before, so will check them out.

    • markbulling

      Hi Ken

      Does subset work with lists? From the documentation, it looks like it only works with vectors, matrices or data frames. Also, I’m trying to get more into the [] notation as I’m a big user of subset.

      Cheers

      Mark

Leave a Reply

Your email address will not be published. Required fields are marked *

Machine Learning and Analytics based in London, UK