This isn't really a httr2 specific problem though it is easy to illustrate this way. If I have a param that is being to a function that I want to lapply
on and that function and the componets of ...
need to named, how do I.... do that? I want the function to take the argument name (i.e. param
below) use that are the dots name with the values of the vector being lapply
over.
library(httr2)
req <- request("http://example.com")
param <- c("foo", "bar")
## hard code param (this is what i am hoping to generate)
lapply(param, \(x) req_url_query(req, param = x))
#> [[1]]
#> <httr2_request>
#> GET http://example.com?param=foo
#> Body: empty
#>
#> [[2]]
#> <httr2_request>
#> GET http://example.com?param=bar
#> Body: empty
## want the ... to dynamically named
my_func <- function(req, ...) {
lapply(..., \(x) req_url_query(req, ...))
}
other_param <- c("x", "y")
my_func(req, other_param)
#> Error in `modify_list()`:
#> ! All components of ... must be named
CodePudding user response:
This looks like it works (edited from comment below):
my_func <- function(req, ...) {
dots <- list(...)
dots_chr <- unlist(dots)
function_string <- paste0("lapply(dots_chr, \\(x) req_url_query(req, ", names(dots), "= x))")
eval(parse(text = function_string))
}
which returns:
$pizza1
<httr2_request>
GET http://example.com?pizza=is_great
Body: empty
$pizza2
<httr2_request>
GET http://example.com?pizza=is_healthy
Body: empty
CodePudding user response:
Here's a version that uses the base do.call
function to build the call to the function with the parameter name you want
my_func <- function(req, ...) {
mc <- as.list(match.call()[-(1:2)])
stopifnot(length(mc)==1)
pname <- deparse1(mc[[1]])
if(!is.null(names(mc))) {
pname[names(mc)!=""] <- names(mc)[[names(mc)!=""]]
}
lapply(list(...)[[1]], \(x) do.call("req_url_query", setNames(list(quote(req), x), c("", pname))))
}
It handles all cases like
other_param <- c("x", "y")
my_func(req, other_param)
my_func(req, other_param=1:2)
my_func(req, other_param=other_param)