How to define a vectorized function in R

Viewed 21812

As the title, I'd like to know how to define a vectorized function in R.

  • Is it just by using a loop in the function?
  • Is this method efficient?
  • And what's the best practice ?
3 Answers

Late to the party, but I think the question is stilly highly relevant and there some new methods gained popularity recently. So ere's one more way to vectorize functions in R, using tidyverse methods.

First, define some data:

x <- c(1,2,3)
y <- c(1,2,4)

Now, assume, we'd like to perform some computation element-wise on these two vectors such that f(x,y).

For instance, computing the sum for each (pair of) element of x and y should yield: 2,4,7.

Let's use map2_dbl from purrr (a package from the tidyverse ecosystem):

x <- c(1,2,3)
y <- c(1,2,4)

library(tidyverse)
map2_dbl(.x = x,
         .y = y,
         .f = sum)
#> [1] 2 4 7

As can be seen, the result is vectorized in the sense that the sum was computed for each pair of elements from x and y.

In sum, using map() and its variants is a convenient way to vectorize functions, at least in some situations.

Related