Skip to content

A thin wrapper around mapply() that iterates over paired .x and .y values. They must have the same length elements but can be any R object to iterate over. Similar to purrr::map2() without having to load the purrr namespace. If .y is missing and .x is named, this is equal to liter(.x, names(.x), ...), which is the behavior of purrr::imap().

Usage

liter(.x, .y = NULL, .f, ...)

Arguments

.x, .y

Vectors or objects of the same length.

.f

A function to be applied to each element of x.

...

Additional arguments passed to .f.

Value

Always returns a list. The returned list is named by the names of .x or by .x itself if possible.

Examples

x <- LETTERS
names(x) <- letters
liter(x, 1:26, paste, sep = "-") |> head()
#> $a
#> [1] "A-1"
#> 
#> $b
#> [1] "B-2"
#> 
#> $c
#> [1] "C-3"
#> 
#> $d
#> [1] "D-4"
#> 
#> $e
#> [1] "E-5"
#> 
#> $f
#> [1] "F-6"
#> 

# .y = NULL; uses names(.x)
liter(x, .f = paste, sep = "-") |> head()
#> $a
#> [1] "A-a"
#> 
#> $b
#> [1] "B-b"
#> 
#> $c
#> [1] "C-c"
#> 
#> $d
#> [1] "D-d"
#> 
#> $e
#> [1] "E-e"
#> 
#> $f
#> [1] "F-f"
#> 

# .y = index 1:3
liter(c("a", "b" , "c"), .f = paste, sep = "=")
#> $a
#> [1] "a=1"
#> 
#> $b
#> [1] "b=2"
#> 
#> $c
#> [1] "c=3"
#> 

# anonymous on-the-fly .f()
liter(1:6, rnorm(6), function(.x, .y) .x + .y^2) |> unlist()
#> [1] 1.011361 3.385127 3.200159 9.166323 5.018512 9.996157