[1] "I"
POP77001 Computer Programming for Social Scientists
Before
After
Everything that happens in R is a function call.
John Chambers
function() to create a function object.function (closure).<function_name> <- function(<arg_1>, <arg_2>, ..., <arg_n>) {
<function_body>
}
body()formals()environment()return() function is encounteredreturn() function call, orreturn() (implicit return), orNULL if no return() and no expressions to evaluate... (Ellipsis)... (aka ellipsis or dot-dot-dot) argument.|>.%>% (magrittr package).[1] 42
<- and <<-= is also supported, it is not recommended.<- assigns to the current environment<<- (super assignment) assigns to the parent environmentlibrary() function.::).base package.stats package.library(<package_name>)
<package_name>::<object_name>
function() does not have to be bound to a name.function() can be easily incorporate into other function calls.apply() family of base R functionals is the most ubiquitous example.for loops. [1] -0.50219235 0.13153117 -0.07891709 0.88678481 0.11697127 0.31863009
[7] -0.58179068 0.71453271 -0.82525943 -0.35986213
apply() Family of Functions| Function | Description | Input Object | Output Object | Simplified |
|---|---|---|---|---|
apply() |
Apply a given function to margins (rows/columns) of input object | matrix/array/data.frame | vector/matrix/array/list | Yes |
lapply() |
Apply a given function to each element of input object | vector/list | list | No |
sapply() |
Same as lapply(), but output is simplified |
vector/list | vector/matrix | Yes |
vapply() |
Same as sapply(), but data type of output is specified |
vector/list | vector | No |
mapply() |
Multivariate version of sapply(), takes multiple objects as input |
vectors/lists | vector/matrix | Yes |
lapply() functionlapply(<input_object>, <function_name>, <arg_1>, ..., <arg_n>)
lapply(): Exampleapply() Function<margin> argument indicates whether function is applied across rows (1) or columns (2)apply(<input_object>, <margin>, <function_name>, <arg_1>, ..., <arg_n>)
apply(): Example [,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
mapply() FunctionMap() calls mapply() without simplification (always returns a list).mapply(<function_name>, <input_object_1>, ..., <input_object_n>, <arg_1>, ..., <arg_n>)
mapply(): Example [,1] [,2] [,3] [,4] [,5]
[1,] -2.0293167 -1.8761800 -1.3153517 0.6355458 0.8910288
[2,] -2.3888542 0.5281212 -2.1606647 8.0295025 2.9145384
[3,] -1.4891437 -0.4760774 0.6928336 0.4482816 4.0866164
[4,] -2.9138142 0.5468092 -3.4731884 0.5552260 7.3270116
[5,] 0.3102968 -2.6287582 0.7412280 -1.7600573 6.8510101
The three main criteria of functional programming as a computing paradigm are: