Where to begin…

Filtering a list with the Filter higher-order function

Posted on January 26, 2012 by

Last week markbulling over at Drunks & Lampposts posted a method of using `sapply` to filter a list by a predicate. Today the @RLangTip tip of the day was to use `sapply` similarly. This made makes me wonder if R‘s very useful higher-order functions aren’t as well known as they should be. In this case, the `Filter` higher-order function would be the tool to use. `Filter` works more or less like the `*apply` family of functions, but it performs the subsetting (the filtering) of a list based on a predicate in a single step.

As an example, let’s say we have a list of 1000 vectors, each of length 2 with $$x_1,\,x_2 \in [0,\,1]$$, and we want to select only those vectors where the elements of the list sum to a value greater than 1. With `Filter`, this is all we have to do:

```mylist <- lapply(1:1000, function(i) c(runif(1), runif(1)))
method.1 <- Filter(function(x) sum(x) > 1, mylist)```

Which is at least a bit more transparent than the `sapply` alternative:

`method.2 <- mylist[sapply(mylist, function(x) sum(x) > 1)]`

In some very quick tests, I found no performance difference between the two approaches.

There are other useful higher-order functions. If you are interested, check out `?Filter`.

This entry was posted in R. Bookmark the permalink.
{"extraction_info": {"found_math": true, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 1, "mathjax_asciimath": 0, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0}, "config": {"markdown_headings": false, "markdown_code": true, "boilerplate_config": {"ratio_threshold": 0.18, "absolute_threshold": 10, "end_threshold": 15, "enable": true}, "remove_buttons": true, "remove_image_figures": true, "remove_link_clusters": true, "table_config": {"min_rows": 2, "min_cols": 3, "format": "github"}, "remove_chinese": true, "remove_edit_buttons": true, "extract_latex": true}, "english_confidence": 0.9433125257492065, "perplexity_flag": "middle"}