Why use apply?

Intermediate R for Finance

Lore Dirick

Manager of Data Science Curriculum at Flatiron School

Meet the apply family

Function Description
apply Apply functions over array margins
lapply Apply a function over a list or vector
eapply Apply a function over values in an environment
mapply Apply a function to multiple lists or vector arguments
rapply Recursively apply a function to a list
tapply Apply a function over a ragged array
sapply Simplify the result from lapply
vapply Strictly simplify the result from lapply
Intermediate R for Finance

Meet the apply family

Function Description
apply Apply functions over array margins
lapply Apply a function over a list or vector
eapply Apply a function over values in an environment
mapply Apply a function to multiple lists or vector arguments
rapply Recursively apply a function to a list
tapply Apply a function over a ragged array
sapply Simplify the result from lapply
vapply Strictly simplify the result from lapply
Intermediate R for Finance

Meet the apply family

Function Description
apply Apply functions over array margins
lapply Apply a function over a list or vector
eapply Apply a function over values in an environment
mapply Apply a function to multiple lists or vector arguments
rapply Recursively apply a function to a list
tapply Apply a function over a ragged array
sapply Simplify the result from lapply
vapply Strictly simplify the result from lapply
Intermediate R for Finance

lapply()

stock_list <- list(stock_name = "Apple", ticker = "AAPL", 
                   price = 126.5, good_deal = TRUE)

lapply(stock_list, FUN = class)
$stock_name
"character"

$ticker
"character"

$price
"numeric"

$good_deal
"logical"
Intermediate R for Finance

Break it down

ch5_vid1_slides.015.png

Intermediate R for Finance

Break it down

ch5_vid1_slides.016.png

Intermediate R for Finance

Break it down

ch5_vid1_slides.017.png

Intermediate R for Finance

Sharpe ratio

$sharpe = \frac{mean(r) - r_f}{sd(r)}$

  • Normalize returns by risk
  • Compare returns among stocks
  • Higher sharpe ratio = More return / unit risk
Intermediate R for Finance

Let's practice!

Intermediate R for Finance

Preparing Video For Download...