# NOT RUN {
# Let's create a function that takes a variable number of arguments:
numeric <- function(...) {
dots <- list2(...)
num <- as.numeric(dots)
set_names(num, names(dots))
}
numeric(1, 2, 3)
# The main difference with list(...) is that list2(...) enables
# the `!!!` syntax to splice lists:
x <- list(2, 3)
numeric(1, !!! x, 4)
# As well as unquoting of names:
nm <- "yup!"
numeric(!!nm := 1)
# One useful application of splicing is to work around exact and
# partial matching of arguments. Let's create a function taking
# named arguments and dots:
fn <- function(data, ...) {
list2(...)
}
# You normally cannot pass an argument named `data` through the dots
# as it will match `fn`'s `data` argument. The splicing syntax
# provides a workaround:
fn("wrong!", data = letters) # exact matching of `data`
fn("wrong!", dat = letters) # partial matching of `data`
fn(some_data, !!! list(data = letters)) # no matching
# }
Run the code above in your browser using DataLab