Get all Parameters as List

Viewed 45954

Does R provide an object/function/method/keyword to get all function arguments?

Using an example: function(a, b="default", ...) would provide a and b as well as ... within the function environment. Is there a statement similar to list(...) that would also include a and b in the result?

Or put yet another way: a shorthand for list(a=a, b=b, ...), given function(a, b, ...)

7 Answers

rlang::fn_fmls gives a brief and clean solution:

library(ggplot2)
library(rlang)

# action
argument_list <- rlang::fn_fmls(fn = geom_point)

# evaluate output
class(argument_list)
#> [1] "pairlist"

is.list(argument_list)
#> [1] TRUE

argument_list
#> $mapping
#> NULL
#> 
#> $data
#> NULL
#> 
#> $stat
#> [1] "identity"
#> 
#> $position
#> [1] "identity"
#> 
#> $...
#> 
#> 
#> $na.rm
#> [1] FALSE
#> 
#> $show.legend
#> [1] NA
#> 
#> $inherit.aes
#> [1] TRUE

Created on 2020-02-25 by the reprex package (v0.3.0)

test <- function(
  x = 1,
  y = 2,
  ...
) {
  if(length(list(...)) == 0) {
    print(as.list(environment()))
  } else {
    print(c(as.list(environment()), list(...)))
  }
}

test()
test(z = 3)
Related