Splicing list into dots

rlang

#1

I’m only slowly getting versed in rlang, and I think there might be an rlang ‘solution’ to this situation: I want to call a function with only some of the args coming from a list, the rest being specified in the raw function call. As an example, let’s say want to connect to some database with mostly fixed parameters read in by a config file, but varying one final connection param at run-time (e.g. changing the username during interactive use).

params <- list(
  drv = RPostgres::Postgres()
 ,host = "myhost.mydomain.mytld"
 ,port = 5432
 ,dbname = "mydbname"
) ## normally read in from some config file

The ugly solution

And now I want to connect as user “user1”. One ugly way to do this is:

DBI::dbConnect(params$drv, host = params$host, port = params$port, dbname = params$dbname, user = "user1")

… or the slightly less-verbose:

with(params, DBI::dbConnect(drv, host = host, port = port, dbname = dbname, user = "user1")

The do.call solution

But usually I just end up using do.call like so:

do.call(DBI::dbConnect, c(params, user = "user1"))

Is there an rlang solution?

Is there a ‘trick’ with rlang where I can get the best of both of these worlds? I’m imagining some function (or syntactic sugar) like undots, that conceptually would fill-in dbConnect's dots argument with a list’s contents, like so:

DBI::dbConnect(undots(params), user = "user1")

I’ve only just started working with rlang, and I believe I could write a wrapper for dbConnect to deal with my use case, but I’m hoping there might already be something that I’m just missing here that works for the general case.


#2

The purrrr :package: contains a handy partial function for helping with that. It allows to pre-fill some arguments. see
http://purrr.tidyverse.org/reference/partial.html

In your case, something like this should help you

dbConnect_custom <- purrr::partial(DBI::dbConnect, drv = RPostgres::Postgres(), host = "myhost.mydomain.mytld", port = 5432,dbname = "mydbname")

would allow you to use then dbConnect_custom to fill with other non fixed arguments.