vapply() vs. sapply()
In the last example, sapply() failed to simplify because the date element of market_crash2 had two classes (POSIXct and POSIXt). Notice, however, that no error was thrown! If a function you had written expected a simplified vector to be returned by sapply(), this would be confusing.
To account for this, there is a more strict apply function called vapply(), which contains an extra argument FUN.VALUE where you can specify the type and length of the output that should be returned each time your applied function is called.
If you expected the return value of class() to be a character vector of length 1, you can specify that using vapply():
vapply(market_crash, class, FUN.VALUE = character(1))
dow_jones_drop date
"numeric" "Date"
Other examples of FUN.VALUE might be numeric(2) or logical(1). market_crash2 is again defined for you.
This exercise is part of the course
Intermediate R for Finance
Exercise instructions
- Use
sapply()again to find theclass()ofmarket_crash2elements. Notice how it returns a list and not an error. - Use
vapply()onmarket_crash2to find theclass(). SpecifyFUN.VALUE = character(1). It should appropriately fail.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Market crash with as.POSIXct()
market_crash2 <- list(dow_jones_drop = 777.68,
date = as.POSIXct("2008-09-28"))
# Find the classes with sapply()
___
# Find the classes with vapply()
___