Search code examples
rvectorrandomdifferenceseq

Create a vector of different sequence repeated with runif and rnorm


I want to do something like :

vector <-  c(runif(3),rnorm(1), runif(3), rnorm(1)) 

I've tried :

vector <- rep( c(runif(3), rnorm(1) ), times = 2) )

But the problem is that it's two times the same sequence.

If you can help me please.

Have a nice day


Solution

  • This is exactly what replicate is meant for.
    From the help('replicate') page (my emphasis):

    replicate is a wrapper for the common use of sapply for repeated evaluation of an expression (which will usually involve random number generation).

    set.seed(1234)
    vector <-  replicate(2, c(runif(3),rnorm(1)))
    vector
    #          [,1]        [,2]
    #[1,] 0.1137034 0.640310605
    #[2,] 0.6222994 0.009495756
    #[3,] 0.6092747 0.232550506
    #[4,] 0.3143686 0.429124689
    

    Edit

    After the explanation in this comment, I believe the follwing is closer to what the question asks for. Note that each matrix 2x2 has the elements in the previous output in the correct order.

    set.seed(1234)
    W <- array(dim = c(2, 2, 2))
    W[] <- replicate(2, c(runif(3), rnorm(1)))
    W
    #, , 1
    #
    #          [,1]      [,2]
    #[1,] 0.1137034 0.6092747
    #[2,] 0.6222994 0.3143686
    #
    #, , 2
    #
    #            [,1]      [,2]
    #[1,] 0.640310605 0.2325505
    #[2,] 0.009495756 0.4291247