How to randomly generate random numbers in one of two intervals I am trying to generate random numbers with R, uniformly from one of two different intervals. I want the numbers to be generated, for example, in the intervals [-0.8,-0.4] or [0.3,0.9].
I am trying to play by using more runif together, but I have problems when the intervals are not of the same size.
Can you please help?
 A: From what I understand, you want to to simulate data uniformly from the set $[a,b]\cup [c,d]$ with $a< b < c < d$.
There are several ways to do this, but this will do the trick. 
 y <- runif(1, 0, b-a+d-c)
 if( y < (b-a) ){
    x <- a + y
 }else{
    x <- c + y - (b-a)
 }

Here is a quick example using the numbers from your original post.

A: Consider using rejection sampling. Generate realizations of a uniform distribution over the whole interval, then reject any that are in the middle part you're not interested in. 
If this is too inefficient (because the rejection region is not small compared to the whole interval), you could do it in two stages, a weighted Bernoulli coin flip (based on the relative size of the regions) to choose which region you sample from, then uniform inside that.
This might look like (for your example, I hard-coded in the boundaries which is not great practice)
n_samp <- 1e5

# Rejection sampling
sample_a <- runif(n_samp, -0.8, 0.9)
accepted_sample_a <- sample_a[!(sample_a > -0.4 & sample_a < 0.3)]

hist(accepted_sample_a)

cat("Sampling efficiency:", length(accepted_sample_a)/length(sample_a))

# Bernoulli-uniform
weight <- (-0.4 - -0.8)/((-0.4 - -0.8) + (0.9 - 0.3))
which_region <- rbinom(n_samp, 1, prob = weight)
sample_b <- runif(n_samp, ifelse(which_region, -0.8, 0.3), ifelse(which_region, -0.4, 0.9))

hist(sample_b)

A: You can also use the following for each range, then join the ranges together.  This method avoids rejection of any samples.
n <- 1e5 # set the desired number of samples
a <- (-0.8); b <- (-0.4); c <- 0.3; d <- 0.9 # set ranges

p <- (b-a)/(b-a+c-d)
n1 <- binom(1,n,p)
n2 <- n-n1

low <- runif(n1)*(b-a)+a # create lower random number sample
high <- runif(n2)*(d-c)+c # create upper random sample
rand.unif <- paste(low,high) # join samples together

rand.unif <- sample(rand.unif) # randomize sample after generation.

Edit: n1 and n2 calculations added to correct probability of each selection, with n set to cover the entire dataset.  The sample size is based upon the binomial distribution, thanks to an excellent suggestion in the comments.
If time-series is important, you can reorder the vector with rand.unif <- sample(rand.unif) to give you a random time series with a fixed number of samples of each distribution.
