you're reading...

R: Subsetting a list based on a condition

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]
About these ads


5 thoughts on “R: Subsetting a list based on a condition

  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.

    Posted by Jason | January 20, 2012, 12:44 am
  2. Another option is the subset() function.

    Posted by Ken | January 26, 2012, 1:19 am
    • 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.



      Posted by markbulling | January 26, 2012, 8:10 pm


  1. Pingback: Filtering a list with the Filter higher-order function | Left Censored - January 27, 2012

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog Stats

  • 287,992 hits

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 480 other followers


Get every new post delivered to your Inbox.

Join 480 other followers

%d bloggers like this: