0

I am currently building a tool for university and need to run a loop over an if else statement and store the results in new variables. Would be great if you would have some advice for me.

The main idea of the tool is to simulate values of on data frame based on the user-input of another data frame. The user can decide between normal, triangle, etc. distribution.

What I need help with is the loop that changes on the one hand the new variable and on the other hand through the several columns of the first data frame.

This is my code so far:

runs = 10000
count.guv <- 3
count.distr <-  1

for (i in distribution){
  if(distribution[i]==1){
    sim.price.dev[i] <- rnorm(runs,mean = mean(data.matrix(df.guv.fiktiv[count.guv]), sd = sd(data.matrix(df.guv.fiktiv[count.guv]))))
  } else if (distribution[i]==2){
    sim.price.dev[i] <- rtriangle(runs,-0.05,0.05,mean(data.matrix(df.guv.fiktiv[count.guv])))
  }   else if (distribution[i]==3){
    sim.price.dev[i] <- runif(runs,min=-0.05,max=0.05)
  }    else if (distribution[i]==4){
    sim.price.dev[i] <- rlnorm(runs,meanlog = mean(log(data.matrix(df.guv.fiktiv[count.guv]))), sdlog = sd(log(data.matrix(df.guv.fiktiv[count.guv]))))
  }      else if (distribution[i]==5){
    sim.price.dev[i] <- df.guv.fiktiv[nrow(df.guv.fiktiv),count.guv]
} else {
    sim.price.dev&i <- df.guv.fiktiv[nrow(df.guv.fiktiv),count.guv]
  }
  count.guv <- count.guv+1
}
hahlhorn
  • 1
  • 1
  • 1
    I'm not clear on your problem. Does `sim.price.dev` update something? Perhaps you could show us your attempt at the loop you mention. – WaltS May 19 '20 at 13:01
  • Have a look at `ifelse()` instead of `if / else` . It is vectorised and you will not need a for loop – Sotos May 20 '20 at 07:19
  • Thanks for your reply. I just updated my code with a few things I worked on yesterday. `sim.price.dev` is my target variable for the output of the loop. I need a way to change that target during the loop like `sim.price.dev1`, `sim.price.dev2`, etc. Is that possible? – hahlhorn May 20 '20 at 07:22
  • What do you mean by that @Sotos? As I'm still a total newcomer, I might ask so stupid questions. – hahlhorn May 20 '20 at 07:24
  • I mean that you can do it without a for loop. Try `ifelse(distribution == 1, ..., ifelse(distribution == 2, ..., ifelse(distribution == 3, ..., ...)))`. [Here is a link](https://stackoverflow.com/questions/18012222/nested-ifelse-statement) explaining how to do nested ifelse – Sotos May 20 '20 at 07:28

0 Answers0