0

I have very simple question, lets say i have function that generates random integer from chosen range, without generating zero. It goes like this:

customfunction=function(minv,maxv){
  value=floor(runif(1,min=minv,max=maxv))
  repeat {
    if (value<0){break}
    else if(value>0){break}
    else {value=floor(runif(1,min=minv,max=maxv))}
  }
  print(value)
}

Very simple. What i want to do is to make the part that restricts my function from generating zero to be just one sentence for example zero_restriction, in MY HEAD it would look like this:

customfunction=function(minv,maxv){
 value=floor(runif(1,min=minv,max=maxv))
 zero_restriction
  print(value)
}

Is this possible? Or is it too much of workaround to be worth? The point is I am going to have couple of functions each with certain restrictions, so i thought simplifying them to one word would be more convenient.

2 Answers 2

2

If you are just using integers, one approach would be to exclude the values you don't want (such as 0) and use sample rather than runif...

customfunction <- function(minv,maxv){
  excl <- c(0) #values to exclude
  range <- seq(minv,maxv)
  range <- range[-which(range %in% excl)]
  return(sample(range,1))
}
Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunetly I will not be using only integers. I should emphasize at first post that this is only my training function, later on I want my function to take any value except 0.
This approach would work with any discrete set of values - not just integers - you just need to replace the seq with something that defines the set. If you're planning to use real values then your chances of getting a zero are infinitesimal!
0

You may also consider applying a while loop e.g.

while((r <- floor(runif(1, min, max))) == 0) {  }
print(r)

This may not be the most readable solution, but it will generate new random values, as long r is set to 0, and stop doing it after it is set to a non zero value.

1 Comment

as I just read you wont only be sampling integers. In this case this approach still works but I'd suggest a condition more like abs(x) < 1e-6 and not an exact == test

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.