How to Vectorize a function in R RStudio

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)

3 Likes