knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.path = "man/figures/README-",
  out.width = "100%"
)

eList

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:

Installation

You can install the released version of eList from CRAN with:

install.packages("eList")

Examples

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)


cmann3/eList documentation built on Jan. 25, 2021, 6:17 a.m.