R - vapply(): safer version of sapply()

25 Dec 2018

Other apply functions:

vapply

Has a pre-specified type of return value, so it can be safer (and sometimes faster) to use. Works similarly to sapply, except that it requires an extra parameter specifying the type of the expected return value. Useful in coding: can help ensure silent errors don’t cause issues.

<a href=https://www.r-bloggers.com/those-other-apply-functions>https://www.r-bloggers.com/those-other-apply-functions</a>

sample_list <- list(10, 20, 30, "some_string")

sapply(sample_list, max)
# "10"          "20"          "30"          "some_string"

vapply(sample_list, max, numeric(1))
# Error in vapply(sample_list, max, numeric(1)) : 
#  values must be type 'double',
# but FUN(X[[4]]) result is type 'character'

# -> the 3d parameter, numeric(1) specifies that we want the output returned by vapply to be numeric. 
# This means if an issue occurs in returning a numeric result, vapply will result in an error, rather than trying to coerce the result to a different data type. 
[ R  apply  list  function  ]