# [R] How to vectorize this function

David L Carlson dc@r|@on @end|ng |rom t@mu@edu
Thu Sep 20 18:05:12 CEST 2018

```Your function takes an argument "F" that is never used and uses an object "y" which is not defined. Give us some data to use for testing different approaches along with the answer you expect. It may be possible to use two ifelse() functions instead of the loop.

----------------------------------------
David L Carlson
Department of Anthropology
Texas A&M University
College Station, TX 77843-4352

-----Original Message-----
From: R-help <r-help-bounces using r-project.org> On Behalf Of Lynette Chang
Sent: Thursday, September 20, 2018 10:09 AM
To: r-help using r-project.org
Subject: [R] How to vectorize this function

Hello everyone,

I’ve a function with five input argument and one output number.
impVolC <- function(callM, K, T, F, r)

I hope this function can take five vectors as input, then return one vector as output. My vectorization ran into problems with the nested if-else operation. As a result, I have to write another for loop to call this function. Can anyone suggest some methods to overcome it? I put my code below, thanks.

impVolC <- function(callM, K, T, F, r){

if(y >= 0){
call0 <- K*exp(-r*T)*(exp(y)*polya(sqrt(2*y)) - 0.5)
if(callM <= call0){
sig <- 1/sqrt(T)*(sqrt(gamma + y) - sqrt(gamma - y))
}else{
sig <- 1/sqrt(T)*(sqrt(gamma + y) + sqrt(gamma - y))
}
}else{
call0 <- K*exp(-r*T)*(exp(y)/2 - polya(-sqrt(-2*y)))
if(callM <= call0){
sig <- 1/sqrt(T)*(-sqrt(gamma + y) + sqrt(gamma - y))
}else{
sig <- 1/sqrt(T)*(sqrt(gamma + y) + sqrt(gamma - y))
}
}
sig
}

for(i in 1:length(call)){
sigV[i] <- impVolC(callM = call[i], K = df\$Strike[i], T = T, F = F, r = r_m) }

______________________________________________
R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see https://stat.ethz.ch/mailman/listinfo/r-help