10  A Simple Function

10.1 Function structure

  • All R functions have three parts:
  • the body(), the code inside the function.
  • the formals(), the list of arguments which controls how you can call the function.
  • the environment(), the map of the location of the function’s variables.

10.2 A simple function structure

  • Function assignment
  • Function assignment with and without ()
  • Function outputs
  • Function with return
  • Function with mandatory and default arguments
Code
fn_mean = function(x) {
    xn = length(x)
    xsum = sum(x)
    xmean = xsum/xn
    return(xmean)
}

10.3 Data

Code
A = c(11, 12, 15, 14, 18)

B = c(NA, 12, 15, 14, 18)

10.4 Class

Code
class(fn_mean)
[1] "function"

10.5 Function argument

Code
formals(fn_mean)
$x

10.6 Function body

Code
body(fn_mean)
{
    xn = length(x)
    xsum = sum(x)
    xmean = xsum/xn
    return(xmean)
}

10.7 Function environment

Code
environment(fn_mean)
<environment: R_GlobalEnv>

10.8 Call a function

Code
fn_mean(A)
[1] 14

10.9 Assign a function outcome

Code
A_mean = fn_mean(A)

A_mean
[1] 14

10.10 Another call

Code
fn_mean(B)
[1] NA

10.11 Function structure

Code
import numpy as np

def fn_mean(x): 
  xn = len(x) 
  xsum = np.sum(x) 
  xmean = xsum / xn 
  return xmean

A = [11, 12, 15, 14, 18]

fn_mean(A)