2026-01-15
We use functions all the time
What if there isn’t a built-in or package function?
Idea: avoid repetitive coding (errors, hard to maintain)
Instead:
Name
Input arguments
Body
Output values
we want to deal with missing values more gracefully
Parameters can have default values. Those values are included in the function specification
Condition is a logical value (TRUE or FALSE), i.e. has to be of length 1
Use & and | to combine several conditions
! negates a condition (!FALSE is TRUE)
If statement block diagram
If-else statement block diagram
Start simple, then extend
Test out each step
Don’t try too much at once
Write a function sd that computes the standard deviation of x “from scratch”. Include a parameter na.rm in it
\(L(\lambda; x) = -n\lambda + log(\lambda) \cdot\sum x_i\) is the log likelihood function of a Poisson variable x with parameter \(\lambda > 0\)
loglikpois with parameters lambda and x (a vector) that computes the log likelihood value for lambda given observations x.lambda is positive; return an error message (using stop()) if it is not.x = c(1, 3, 2, 3, 0, 1, 0, 1, 3, 3)Use tabs to structure blocks of statements
Build complex blocks of codes step by step
# write comments!
also called lambda expressions
have the form
function (x) do something in one line or function (x) {
do
something
in
multiple
lines
}created on-the-fly, not re-used anywhere else, not assigned a name