Learn R Programming

deduped (version 0.3.0)

with_deduped: Deduplicate the first argument in an expression

Description

This is a convenience wrapper for deduped() to allow it to be piped into an expression. It will recursively parse the first arguments of the expression call tree to find the bottom -- when the first argument is not itself a function call.

  • Without nesting: f(x, ...) |> with_deduped() is equivalent to deduped(\(.z) f(.z, ...))(x).

  • With nesting: f(g(x, g2), f2) |> with_deduped() is equivalent to deduped(\(.z) f(g(.z, g2), f2))(x).

Usage

with_deduped(expr, env = parent.frame())

Value

The result of evaluating the expression.

Arguments

expr

The expression to evaluate.

env

The environment within which to evaluate the expression. Can be modified when calling inside other functions.

Examples

Run this code

x <- sample(LETTERS, 10)
x

large_x <- sample(rep(x, 10))
length(large_x)

slow_func <- function(x) {
  for (i in x) {
    Sys.sleep(0.001)
  }
  tolower(x)
}

system.time({
  y1 <- slow_func(large_x)
})


system.time({
  y2 <- with_deduped(slow_func(large_x))

  # Can also use the R pipe (R >= 4.1.0) or magrittr pipe, for convenience.
  # slow_func(large_x) |> with_deduped()
})

all(y1 == y2)

Run the code above in your browser using DataLab