mercredi 7 mars 2018

For-Loop in R with if-else: How to save the output

I am trying to save the output of the code below. I know "print" is the problem, but I do not know what works instead.

I generally wonder if there is not another way instead of the for-loop: For each value in the vector (x), I want to draw a new random number (here with runif) and match it to a given value (here for example 0.5). Depending on the result, a new value for x should be stored in a vector x2 (similar to the if-else example below). Waiving the for-loop, I could not find a way to always draw a new random number for each value in vector x. I would be very grateful for any help!

x <- c(2,2,2,3,3,3)

for(i in x){
  if(runif(1) <= 0.5){
    print(i + 1)
  } else {
    print(i)
  }
}

Aucun commentaire:

Enregistrer un commentaire