Intro Thoughts

Status Quo

library(tidyverse)

Experiment

  1. What are the three components of a function?

The formals(), the list of arguments that control how you call the function.

The body(), the code inside the function.

The environment(), the data structure that determines how the function finds the values associated with the names.

  1. What does the following code return?
x <- 10
f1 <- function(x) {
  function() {
    x + 10
  }
}


f1(x = 1)()
## [1] 11
f1(1)
## function() {
##     x + 10
##   }
## <bytecode: 0x7fb2706f8560>
## <environment: 0x7fb26e93c7a0>
  1. How would you usually write this code?
`+`(1, `*`(2, 3))
## [1] 7
2*3 + 1
## [1] 7
  1. easier to read?
# trim, na.rm, x
mean(, TRUE, x = c(1:10, NA))
## [1] 5.5
# explicit
mean(trim = 0, na.rm = TRUE, x = c(1:10, NA))
## [1] 5.5
# moving to usual positions
mean(c(1:10, NA), na.rm = T)
## [1] 5.5

Does the following code throw an error when executed? Why or why not?

f2 <- function(a, b) {
  a * 10
}

f2(a = 10, b = stop("This is an error!"))
## [1] 100
f2(a = stop("This is an error"))
## Error in f2(a = stop("This is an error")): This is an error

What is an infix function? How do you write it? What’s a replacement function? How do you write it?

Infix functions get their name from the fact the function name comes inbetween its arguments, and hence have two arguments. R comes with a number of built-in infix operators

replacement: functions that replace values by assignment, like names(df) <- c(“a”, “b”, “c”) . They actually look like prefix functions.

replace() function in R Programming Language is used to replace the values in the specified string vector x with indices given in the list by those given in values.


# bind function to a name
myfun <- function(x){x + 1}

# don't

# fun in a list
funs <- list(
  half = function(x) x / 2,
  double = function(x) x * 2
)

funs$double(10)
## [1] 20

do.call

args <- list(x = 1:10, na.rm = TRUE)


do.call(mean, args)
## [1] 5.5

```

How do you ensure that cleanup action occurs regardless of how a function exits?

Closing remarks, Other Relevant Work, Caveats