How to generate positive numbers using repeat in R

I wrote the code below. The goal is to get only positive numbers. So rnorm(5,2,2)

can produce negative numbers as well, but I want it to only produce positive ones. I used repeat

in for this R

, but it doesn't work correctly. What can you suggest to fix it? Here is the code:

for (i in 1:5){
repeat{
x <- rnorm(5,2,2)
if ((length(which(x<0)))==0){break}
print(x)
}
}

      

+3


source to share


2 answers


The original code works. You are probably confused by the print (x) which does not represent the end result



repeat {
    x <- rnorm(5,2,2)
    if ((length(which(x<0)))==0){break}
}
x

      

+3


source


Well, I'm not sure why you are doing this or what you want to achieve exactly, but if you want to sample 100 values โ€‹โ€‹iteratively from the (2,2) normal distribution and repeat until all the values โ€‹โ€‹are positive, you can do something- something like:



v <- rnorm(100,2,2)
nb <- sum(v<0)
while (nb>0) {
  v[v<0] <- rnorm(nb,2,2)
  nb <- sum(v<0)
}

      

+2


source







All Articles