R Dots Arguments
The dots argument, written ..., collects any extra arguments a call passes. A function can inspect the dots, count them, or pass them on.
Collect the dots in a list
collect has no named arguments at all. Every value in the call lands in the list that list(...) builds.
collect <- function(...) {
list(...)
}
print(collect(10, 20, 30))
print(collect("a", "b"))Count the dots
count_dots builds the list of dots and measures its length. A call with no extra arguments counts zero.
count_dots <- function(...) {
length(list(...))
}
print(count_dots(5, 6, 7, 8))
print(count_dots())Add the dots with sum
sum(...) folds all the extra arguments into one total. The same function adds two numbers or three.
total <- function(...) {
sum(...)
}
print(total(4, 8, 15))
print(total(100, 23))Forward the dots to another call
shout writes ... inside the paste0 call, so the marks travel on. With no extra arguments, nothing is added.
shout <- function(text, ...) {
paste0(toupper(text), ...)
}
print(shout("go", "!", "!"))
print(shout("ready"))Example
label_total <- function(label, ...) {
total <- sum(...)
cat(label, "total is", total, "\n")
}
label_total("Team", 12, 18, 10)
label_total("Crew", 7, 8)Key points
- ... in a function definition means the function accepts extra arguments.
- list(...) gathers the extra arguments into a list.
- length(list(...)) counts how many extra arguments arrived.
- A call with no extra arguments gives a count of zero.
- sum(...) adds the extra arguments when they are numbers.
- A function forwards its dots by writing ... inside another call.
In this example the label is a named argument and the scores arrive through the dots. sum(...) folds the scores, and cat prints the label with the total.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
A function is defined as total <- function(...) { sum(...) }. What does total(4, 8, 15) print?