How to Vectorize a function in R RStudio

Hello,

could you help, please, to write a function which returns outcomes as
a list of vectors?

funct.x <- function(x, x1, x2) { 
result = NULL 
for(n in 1:x) { 
result[n] = x[n]*x1+(1 -x[n])*x2 
}#end for loop 
return(result) 
}#end of function

I'm trying to vectorize the function here:

funct.x.vectorized <- Vectorize(funct.x)
f <- funct.x.vectorized(c(0.1, 0.2, 0.3), c(1,2,3), c(4,5,6))

What I understand is I need to take each value from vector x and
multiply it by values from other vectors like this:

0.11 + 0.94

0.22 + 0.85

0.33 + 0.76

And return it as a list of vectors of the outcomes. It does work if x
is a single value, but if x is a vector, everything fails.

Thank you in advance.

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)

2 Likes

Hi, StatSteph,
thank you very much for your reply. You are right, my initial function is wrong,

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.