mercredi 14 août 2019

Creating a Data frame from a for loop in R with an if-else statement inside

I am trying to create a Data Frame out of a For loop with different if-else statements, as some values on the random_growth can be negative and it would not be applied if I do the straight formula. So I came up with this loop but somehow the calculations are wrong.

I would like to have a data frame of 6 columns and 10.000 rows and that if the percentage is negative, it should be able to decrease in every iteration, however because the simbols - and + in the formula it just creates a decrease followed by an increase and so on. I know my loop is not the best way of doing such calculation, but I didn't find another way. Please, I would be really glad if you could help me.

random_growth <- rnorm(n=10000, mean=0.11, sd=0.3560766)
fcf0 <- 3619
ffcfs <- data.frame()
  for (i in random_growth){
    if (i>0){
  fcf1= fcf0*(1+i)
  fcf2= fcf1*(1+i)
  fcf3= fcf2*(1+i)
  fcf4= fcf3*(1+i)
  fcf5= fcf4*(1+i)
  fcf6= fcf5*(1+i)
    }
  else{
  fcf1= if ((fcf0*i)>0){fcf0*(1+i)} else {fcf0-(fcf0*i)}
  fcf2= if ((fcf1*i)>0){fcf1*(1+i)} else {fcf1-(fcf1*i)}
  fcf3= if ((fcf2*i)>0){fcf2*(1+i)} else {fcf2-(fcf2*i)}
  fcf4= if ((fcf3*i)>0){fcf3*(1+i)} else {fcf3-(fcf3*i)}
  fcf5= if ((fcf4*i)>0){fcf4*(1+i)} else {fcf4-(fcf4*i)}
  fcf6= if ((fcf5*i)>0){fcf5*(1+i)} else {fcf5-(fcf5*i)}
  }
  row_i = c(fcf1,fcf2,fcf3,fcf4,fcf5,fcf6)
  ffcfs = rbind(ffcfs,row_i)
    }

Could you help me to identify what is wrong?? Thank you very much!!

Aucun commentaire:

Enregistrer un commentaire