create_n_fn {rearrr}R Documentation

Create n_fn function

Description

[Experimental]

Creates a function that applies a supplied function to all input vectors, or their indices, and rounds the results.

As used with roll_elements(). E.g. to find the the median index in a subset of a grouped data.frame.

Usage

create_n_fn(fn, use_index = FALSE, negate = FALSE, round_fn = round, ...)

Arguments

fn

Function to apply to each dimension. Should return a numeric scalar.

use_index

Whether to apply `fn` to the indices of the vectors. (Logical)

The indices are created with seq_along(x).

negate

Whether to negate the result. I.e. to multiply it with -1. (Logical)

round_fn

Function for rounding results of `fn`.

Rounding is done prior to negation.

E.g. round, floor, or ceiling.

To avoid rounding, supply identity.

...

Arguments for `fn`. E.g. `na.rm = TRUE`.

Value

Function with the dots (`...`) argument that applies the `fn` function to each element in `...` (or indices thereof) (usually one vector per dimension). The results are rounded with `round_fn`.

Note: The dots argument in the generated function should not to be confused with the dots argument in create_n_fn()).

Author(s)

Ludvig Renbo Olsen, r-pkgs@ludvigolsen.dk

See Also

Other n functions: median_index()

Other function creators: create_dimming_fn(), create_origin_fn()

Examples

# Attach packages
library(rearrr)

# Set seed
set.seed(1)

# Create three vectors
x <- runif(10)
y <- runif(10)
z <- runif(10)

# Create n_fn that gets the median index
# and rounds down with floor()
median_index_fn <- create_n_fn(median, use_index = TRUE, round_fn = floor)

# Use median_index_fn
median_index_fn(x, y, z)

# Create n_fn that gets the median of each dimension
median_n_fn <- create_n_fn(median)

# Use median_origin_fn
median_n_fn(x, y, z)

# Should be the same as
round(c(median(x), median(y), median(z)))

# Use mean and ignore missing values
mean_n_fn <- create_n_fn(mean, na.rm = TRUE)

# Add missing values
x[[2]] <- NA
y[[5]] <- NA

# Use mean_n_fn
mean_n_fn(x, y, z)

# Should be the same as
round(c(
  mean(x, na.rm = TRUE),
  mean(y, na.rm = TRUE),
  mean(z, na.rm = TRUE)
))

[Package rearrr version 0.3.4 Index]