knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.path = "man/figures/README-", out.width = "100%" )
Write list comprehensions in R!
The eList package allows users to write vectorized for
loops and contains a variety
of tools for working with lists and other vectors. Just wrap a normal for
loop
within one of the comprehension functions, such as List()
, and let the package
do the rest.
Features include, but are not limited to:
"."
to separate names.if
, else
statements to filter results.=
., clust =
and the cluster.enum
and items
to access the index or name within the loop, or zip
objects together.for
loops.List(...)
or List[...]
for the comprehension. .
notation for variables) or calls.You can install the released version of eList from CRAN with:
install.packages("eList")
A simple "list" comprehension that accumulates all integer sequences to 4 using the List
function. Though it looks like a for
loop, it is actually using lapply
behind the scenes.
library(eList) List(for (i in 1:4) 1:i)
Loops can be nested and filtered using if
statements. The example below uses Num
to produce a numeric vector rather than a list. Other comprehensions include Chr
for character vectors, Logical
for logical vectors, Vec
for flat (non-list) vectors, etc.
Num(for (i in 1:4) for (j in 3:6) if (i == j) i^2)
Use the "dot" notation to use multiple variables within the loop.
Chr(for (i.j in zip(1:4, 5:8)) paste0(i, j))
Use =
within the loop to assign a name to each item within the list, or other item.
values <- zip(letters[1:4], 5:8) List(for (i.j in values) i = j)
Parallelization is also very easy. Just create a cluster and add it to the comprehension with the clust
argument.
my_cluster <- auto_cluster() x <- Num(for (i in sample(1:100, 50)) sqrt(i), clust = my_cluster) # Close the cluster if not needed! close_cluster(my_cluster) x
Want a statistical summary using a comprehension? eList contains a variety of summary functions for that purpose. Stats
is a general summary comprehension that computes many different values.
Stats(for (i in sample(1:100, 50)) sqrt(i))
eList also contains functional programming style functions for working with lists and other vectors. These functions perform an operation using a function on another object. They are similar to the higher order functions in Base R, but are pipe-friendly, handle a wide ranger of object types, and allow for different methods of specifying functions.
x <- list(1:4, 5:8, 9:12) map(x, mean)
This can also be calculated using formula notation. Formulas can be be written as either a two-sided formula or a one-sided formula by prefixing variables with dots.
# Two-sided Formula map(x, i ~ sqrt(i) + 1) # One-sided Formula map(x, ~ sqrt(.i) + 1)
The higher order functions also accept unevaluated "calls".
round2 <- substitute(round(digits=2)) map(rnorm(5), round2)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.