library(tidyverse)
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.
x <- 10
f1 <- function(x) {
function() {
x + 10
}
}
f1(x = 1)()
## [1] 11
f1(1)
## function() {
## x + 10
## }
## <bytecode: 0x7fb2706f8560>
## <environment: 0x7fb26e93c7a0>
`+`(1, `*`(2, 3))
## [1] 7
2*3 + 1
## [1] 7
# 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
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
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
args <- list(x = 1:10, na.rm = TRUE)
do.call(mean, args)
## [1] 5.5
Given a name, like “mean”, match.fun() lets you find a function. Given a function, can you find its name? Why doesn’t that make sense in R?
It’s possible (although typically not useful) to call an anonymous function. Which of the two approaches below is correct? Why? #
```