Why you should use vapply in R

Why you should use vapply in R

R
In this post we'll cover the vapply function in R. vapply is generally lesser known than the more popular sapply, lapply, and apply functions. However, it is very useful when you know what data type you're expecting to apply a function to as it helps to prevent silent errors. Because of this, it can be more advisable to use vapply rather than sapply or lapply. See more R articles by clicking here Examples Let's take the following example. Here, we have a list of numeric vectors and we want to get the max value of each vector. That's simple enough - we can just use sapply and apply the max function for each vector. [code lang="R"] test <- list(a = c(1, 3, 5), b = c(2,4,6), c = c(9,8,7)) sapply(test,…
Read More
Those “other” apply functions…

Those “other” apply functions…

R
So you know lapply, sapply, and apply...but...what about rapply, vapply, or eapply? These are generally a little less known as far as the apply family of functions in R go, so this post will explore how they work. rapply Let's start with rapply. This function has a couple of different purposes. One is to recursively apply a function to a list. We'll get to that in a moment. The other use of rapply is to a apply a function to only those elements in a list (or columns in a data frame) that belong to a specified class. For example, let's say we have a data frame with a mix of categorical and numeric variables, but we want to evaluate a function only on the numeric variables. Use rapply to…
Read More