In R, the vapply()
function calculates the sum of a list’s elements. The additional “FUN.VALUE” option allows us to specify the output’s type and length each time the applicable function is called.
Let’s understand this with an example. Consider the following code:
A<-c(-1: -10)B<-c(1:5)C<-c("x", "y", "z")lst<-list(A,B,C)sapply(lst, min)
A
, B
, and C
, and create a list called lst
.sapply()
function to apply the min
(or find minimum value) for each vector in lst
.Notice that the sapply()
has no type checking of the expected output. The vector argument C
is a vector of characters. Hence, sapply()
combines (or coerces) the final result as a vector of characters.
To overcome this, we can use vapply()
, which has a type and length that checks the output.
vapply(X, FUN, FUN.VALUE)
X
: This represents a vector-like object.FUN
: This is the function to apply to the provided vector argument. It is a required parameter.FUN.VALUE
: This is where we specify the type of data we are expecting.The vapply()
function returns a list or an array of values.
Let’s look at the code below:
A<-c(-1: -10)B<-c(1:5)C<-c(1, 2, 3)lst<-list(A,B,C)vapply(lst, min, numeric(1))lst$C<-c("x", "y", "z")vapply(lst, min, numeric(1))
A
, B
, and C
, and create a list called lst
.vapply()
to find the minimum of the individual lists in lst
. We specify the expected data type as numeric(1).C
to a vector of characters and invoke vapply()
with the expected data type as numeric(1). The code fails as the expected output type is not numeric
.