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]
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.
Posted by Jason | January 20, 2012, 12:44 amThanks for this Jason. I hadn’t come across Filter() (or any other of the higher level functions) before, so will check them out.
Posted by markbulling | January 23, 2012, 8:47 pmAnother option is the subset() function.
Posted by Ken | January 26, 2012, 1:19 amHi 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
Posted by markbulling | January 26, 2012, 8:10 pm