# # Unit 6 - User-functions # # Additions: default arguments, lazy evaluation, and more # # Default arguments # If we do not pass arguments to # function's parameters, it may # use predefined default arguments. # Must we pass arguments to all parameters? print(rep(x = 3, times = 1)) print(rep(x = 3)) ?rep ?sample # User-functions foo <- function(x = 5, y = 2) { return (x + y) } print(foo(1, 1)) print(foo(1)) print(foo()) # Not all parameters must have default arguments foo <- function(z, y = 2) { return (z + y) } print(foo(1, 1)) print(foo(1)) print(foo()) print(foo(y = 1)) foo <- function(a = 1, b) { return (a + b) } print(foo(2, 1)) print(foo(2)) print(foo()) print(foo(b = 2)) # Lazy evaluation # Let us take another look at this example foo <- function(c = 1, d) { print(c) return (c + d) } print(foo(1)) # Now look at the output of executing this: foo <- function(x = 1, y) { print(x) return (x + y) } print(foo(1)) # Two "See also's" # (I) Take another look at the c function. # The number of arguments passed to it # may vary. # This is done using a special operator, # The ... operator. c(3, 5, 4, 2, 8) c(3, 2, 8) c(3, 5, 4, 2, 8, 9) ?c # (1I) Functions are objects and as arguments goo <- function(x = 5, y = 2) { return (x + y) } print(class(goo)) goo <- function(x) { use x as a function } goo(unique) tapply