How to use the vapply() function in R
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.
Code example 1
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)
Code explanation
- Lines 1-4: We create a list of vector arguments
A,B, andC, and create a list calledlst. - Line 6: We use the
sapply()function to apply themin(or find minimum value) for each vector inlst.
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.
Syntax
vapply(X, FUN, FUN.VALUE)
Parameters
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.
Return value
The vapply() function returns a list or an array of values.
Code example 2
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))
Code explanation
- Lines 1–4: We create a list of vector arguments
A,B, andC, and create a list calledlst. - Line 6: We invoke the
vapply()to find the minimum of the individual lists inlst. We specify the expected data type as numeric(1). - Lines 7-8: We re-assign the value of
Cto a vector of characters and invokevapply()with the expected data type as numeric(1). The code fails as the expected output type is notnumeric.