Hello,

I have been using R for 6 years, but I still do not understand what it means to vectorize a function. I have read a lot about it, yet I feel that I don't know how to implement it. I know that it makes the code run faster, which is why I'm interested to learn.

Can you explain what vectorize a function means? Can you provide a clear examples?

P.S. can someone add vectorize as a tag?

Thank you!

lars
February 16, 2021, 5:08pm
3
And maybe you'll find the example provided in this topic How to Vectorize a function in R RStudio helpful as well.

I think your initial function had an error but we can also simplify this and avoid a loop. First, I'll show you what I think you meant originally and then a vectorized version.
funct.x <- function(x, x1, x2) {
result = rep(NA, length(x))
for(n in 1:length(x)) {
result[n] = x[n]*x1[n]+(1 -x[n])*x2[n]
}#end for loop
return(result)
}#end of function
funct.x.vectorized <- function(x, x1, x2) {
x*x1+(1-x)*x2
}
funct.x(c(0.1, 0.2, 0.3), c(1,2,3), c(4,5,6))
#> [1] 3.7 4.4 5.1
funct.x.vectorized(c(0.1, 0.2, 0.3), c(1,2,3), c(4,5,6))
#> [1] 3.7 4.4 5.1
c(0.1*1 + 0.9*4, 0.2*2 + 0.8*5, 0.3*3 + 0.7*6)
#> [1] 3.7 4.4 5.1
Created on 2019-12-01 by the reprex package (v0.3.0)

joels
February 16, 2021, 5:19pm
4
You might find chapters 3 (Failing to Vectorize) and 4 (Over-vectorizing) of the R Inferno helpful.

system
Closed
March 9, 2021, 5:19pm
5
This topic was automatically closed 21 days after the last reply. New replies are no longer allowed. If you have a query related to it or one of the replies, start a new topic and refer back with a link.