I was trying to execute this functions, but I kept on getting an error with my if statment: Error in if (value[1][i] < 0) { : missing value where TRUE/FALSE needed:
Monte_Carlo <- function(trial)
{
S_T <- S_o*exp((r - q - (1/2)*sigma^2)*period + sigma*rnorm(trial, mean = 0, sd = 1))
K <- matrix(100, nrow = 1, ncol = 20)
value <- K - S_T
for(i in 1:trial)
{
if(value[1][i] < 0)
{
value[1][i] = 0;
}
}
return (mean(value)*exp(-r))
}
You are indexing your matrix incorrectly.
value[1]will return a single value, which you are then trying to assign theithelement of, foriup totrialIf you assign to the
ith element in the 1st row (which looks as if you are trying to do), then it will workyou can remove the
forloop andifstatement withpmaxwhich is vectorized and will return elementwise the maximum of value and 0.As a matter of good programming, I would add
r,S_o,q,sigmaandperiodas arguments to your function, so that it doesn’t depend on global variables