Closed siavash-babaei closed 2 years ago
Can you please make your reprex a bit more minimal? It's not clear to me precisely what problem you're seeing.
Hi, Sorry (for long reprex), and Thank You (for all in everything("tidy")
) @hadley.
Ok, here's an even more minimal reprex:
library(purrr)
fns <- list(rnorm_fn = rnorm, runif_fn = runif)
args <- list(
rnorm_args = list(n = 2, mean = 0, sd = 1),
runif_args = list(n = 2, min = 0, max = 1)
)
# ok
x <- pmap(list(fns = fns, args = args), ~ exec(.x, !!!.y))
# fails
x <- pmap(list(fns = fns, args = args), \(fn, args) exec(fn, !!!args))
#> Error in `pmap()`:
#> ℹ In index: 1.
#> Caused by error in `.f()`:
#> ! unused argument (fns = .l[[1]][[i]])
Created on 2022-10-31 with reprex v2.0.2
You can see the problem a bit more easily if you add ...
to the function you're applying:
x <- pmap(list(fns = fns, args = args), \(fn, args, ...) exec(fn, !!!args))
#> Error in `pmap()`:
#> ℹ In index: 1.
#> Caused by error in `exec()`:
#> ! argument "fn" is missing, with no default
Created on 2022-10-31 with reprex v2.0.2
By design, when the input pmap()
is named, those names are matched to the names of the functions.
It only really works with the formula form by coincidence because of the way that as_mapper()
converts the formula to a function:
as_mapper(~ exec(.x, !!!.y))
#> <lambda>
#> function (..., .x = ..1, .y = ..2, . = ..1)
#> exec(.x, !!!.y)
#> attr(,"class")
#> [1] "rlang_lambda_function" "function"
This is one of the reasons that the dev version recommends against using ~
with pmap()
: https://purrr.tidyverse.org/dev/reference/pmap.html#arguments
Problem:
purrr::pmap
with.f
argument in function format generates strange error..f
argument.When you have named list of lists for the
.l
argument and are using an anonymous function for the.f
argument, you need to use the list names as arguments, e.g., if.l = list(args_list_1 = ..., args_list_2 = ...)
then we must usefunction(arg_list_1, arg_list_2) { ... }
rather than sayfunction(arg_1, arg_2) { ... }
which is what you could do in case you were utilising an un-named list of lists for .l argument .Kind of strange and unnecessary behaviour in my opinion. Comparing this R code with similar OCAML/F#: Pattern matching in R is definitely awkward or maybe ML languages somewhat spoil a person in such regards.
Solution 1: Use names of lists from within the
.l
lists of lists.Solution 2
base
lists rather thantibble
lists to feed the.l
argument.