Functional programming with either *apply
or purrr
is my bread and butter yet I do not understand how pmap
handles function arguments.
- I can use their corresponding variable names (given a data frame as input) and do not have to worry about the order.
- I can be more specific and use them as named arguments
- I can use similar argument names
- Yet I cannot use completely different names.
I've been looking through multiple similar questions yet fell short to find the appropriate answer to
A) what is going on and
B) how can I use arbitrary function argument names?
# dummy data -----------------------------------------------------------------
(iter_tibble <- tibble::tibble(a = 1:2,
b = 3:4,
c = 7:6))
#> # A tibble: 2 x 3
#> a b c
#> <int> <int> <int>
#> 1 1 3 7
#> 2 2 4 6
# pmap it --------------------------------------------------------------------
# standard way
purrr::pmap(iter_tibble, function(a, b, c) {
paste(a, b, c)
})
#> [[1]]
#> [1] "1 3 7"
#>
#> [[2]]
#> [1] "2 4 6"
# switch order
# works and a maps to a, b to b etc
purrr::pmap(iter_tibble, function(b, c, a) {
paste(a, b, c)
})
#> [[1]]
#> [1] "1 3 7"
#>
#> [[2]]
#> [1] "2 4 6"
# name arguments
purrr::pmap(iter_tibble, function(a1 = a, b1 = b, c1 = c) {
paste(a1, b1, c1)
})
#> [[1]]
#> [1] "1 3 7"
#>
#> [[2]]
#> [1] "2 4 6"
# name arguments and switch order
purrr::pmap(iter_tibble, function(b1 = b, c1 = c, asterix = a) {
paste(b1, asterix, c1)
})
#> [[1]]
#> [1] "3 1 7"
#>
#> [[2]]
#> [1] "4 2 6"
# but when using a different initial letter
# ERROR
purrr::pmap(iter_tibble,
purrr::safely(
function(b1 = b, c1 = c, obelix = a) {
paste(b1, obelix, c1)
}
))[1]
#> [[1]]
#> [[1]]$result
#> NULL
#>
#> [[1]]$error
#> <simpleError in .f(...): unused argument (a = 1)>
This behavior is rather different from how arguments can be called in regular R functions where abbreviations are possible (yet bad practice) but extensions are not possible.
# regular function usage -----------------------------------------------------
# abbrevate arguments - no problem
sample(1:4, s = 5, repla = TRUE)
#> [1] 1 3 4 3 1
# extend arguments? nope
sample(1:4, size = 5, replaceeeee = TRUE)
#> Error in sample(1:4, size = 5, replaceeeee = TRUE): unused argument (replaceeeee = TRUE)
My guess Is that the answer is rather about the pmap
call to C than what happens in R.