2

Is there a way to give to R function a sequence of named input arguments (where the name is not specified in the function definition) and to capture that sequence as a named list, similar to python's *kwargs? example: f(first=1, second=2) would capture and use in its body a list(first=1, second=2); but f(third=3, fourth=4, fifth=5) would use a list(third=3, fourth=4, fifth=5). It is of course possible to pass as an argument the list itself. The benefit here is ease of use.

gappy
  • 10,095
  • 14
  • 54
  • 73

2 Answers2

6

For this you can use ..., e.g.:

spam = function(a, b, ...) {
    dots = list(...)
    dots['c']
}
spam(1, 2, c = 3)
# $c
# [1] 3
Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
0

I came from Python too. Sometimes only having dots is not enough because you may want to have a different treatment for args and kwargs (arguments named) :

capture_arg_kwarg <- function(...) {
  dots <- list(...)
  kwargs <- dots[names(dots) != ""]
  args <- dots[names(dots) == ""]
  return(list(kwargs = kwargs, args = args))
}
capture_arg_kwarg(3, x = 'toto', y = 'titi', 8)
#> $kwargs
#> $kwargs$x
#> [1] "toto"
#> 
#> $kwargs$y
#> [1] "titi"
#> 
#> 
#> $args
#> $args[[1]]
#> [1] 3
#> 
#> $args[[2]]
#> [1] 8

Created on 2021-10-15 by the reprex package (v2.0.1)

lejedi76
  • 216
  • 1
  • 5