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
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 to share