Writing functions

Intermediate R for Finance

Lore Dirick

Manager of Data Science Curriculum at Flatiron School

Function structure

func_name <- function(arguments) {
  body
}
Intermediate R for Finance

Add one

add_one <- function(x) {
  x_plus_one <- x + 1
  return(x_plus_one)
}

add_one(7)
8
add_one <- function(x) {
  x + 1
}

add_one(7)
8
Intermediate R for Finance

Using an optional argument

add <- function(x, value = 1) {
  x + value
}

add(7)
8
add(7, value = 3)
10
Intermediate R for Finance

Calculating arithmetic returns

ch4_vid2_slides.027.png

prices <- c(23.4, 23.8, 22.3)

# S_(t) - S(t-1) vector diff(prices)
0.4 -1.5
# S_(t-1) vector
prices[-length(prices)]
23.4 23.8
# Arithmetic returns
diff(prices) / prices[-length(prices)]
0.01709402 -0.06302521
Intermediate R for Finance

Calculating arithmetic returns

prices <- c(23.4, 23.8, 22.3)

arith_returns <- function(x) { diff(x) / x[-length(x)] }
arith_returns(prices)
0.01709402 -0.06302521
Intermediate R for Finance

Let's practice!

Intermediate R for Finance

Preparing Video For Download...