...
to accept any argumentsFunctions carry out a fixed task using the arguments provided:
subtract <- function(value, from) { from - value } subtract(value = 5, from = 3)
[1] -2
subtract(from = 3, value = 5)
[1] -2
Naming the arguments makes it clearer what you are doing.
Make an argument optional by providing a default value:
increase <- function(value, by = 1) { value + by } increase(value = 5, by = 2)
[1] 7
increase(value = 5, by = 1)
[1] 6
increase(value = 5)
[1] 6
...
to accept any argumentsSome functions don’t know what their arguments will be:
plot(x, y) plot(x, y, col="black") plot(x, y, type="l", lty=2)
The extra arguments get passed on to plot.xy()
or some other function, which does then the work.
...
to accept any argumentsSome functions don’t know what their arguments will be:
plot(x, y) plot(x, y, col="black") plot(x, y, type="l", lty=2)
The extra arguments get passed on to plot.xy()
or some other function, which then does the work. It looks a bit like this:
plot <- function(x, y, log = "", ...) { xlabel <- deparse1(substitute(x)) ylabel <- deparse1(substitute(y)) xy <- xy.coords(x, y, xlabel, ylabel, log) plot.xy(xy, ...) }
...
to accept any argumentsHere we do the same in plot_populations()
:
plot_populations <- function(populations, new.graph=TRUE, ylim=NA, lty=1, col=NA, ...) { # -- lots of other code -- if (new.graph) { # When it's a new plot, do labels and legends, etc. plot(time, this.pop, ylim = ylim, xlab = "time", ylab = "population size", type = "l", col = line.cols[index], lty = line.ltys[index], ...) # -- more code -- } else { # Otherwise just draw the lines graphics::lines(time, this.pop, col = line.cols[index], lty = line.ltys[index], ...) } }
run_simple <- function(step_function, latest.df, end.time, ...) { population.df <- latest.df keep.going <- (latest.df$time < end.time) while (keep.going) { data <- step_function(latest.df, ...) latest.df <- data$updated.pop population.df <- rbind(population.df, latest.df) keep.going <- ((latest.df$time < end.time) && (!data$end.experiment)) } row.names(population.df) <- NULL population.df }
rbinom()
rbinom(1, count, prob)
rbinom(1, 50, 0.1)
## [1] 8
rbinom(1, 50, 0.1)
## [1] 5