Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create random vectors of another vector?

Tags:

r

I am performing calculations with constants and vectors (approximate length = 100) for which I need to simulate normal distributions N (with rnorm). For constants (K, with standard deviation = KU) I use rnorm() in the standard way:

    K  <- 2
    KU <- 0.2
    set.seed(123)
    KN <- rnorm(n = 3, mean = K, sd = KU)

what provides a vector of length 3 (KN):

    [1] 1.887905 1.953965 2.311742

Now, I need to do the same thing with a vector (V, standard deviation VU). My first guess is to use:

    V  <- c(1, 2, 3)
    VU <- 0.1 * V
    set.seed(123)
    VN <- rnorm(3, V, VU)

but only a vector of 3 elements is produced, one for each vector element:

    [1] 0.9439524 1.9539645 3.4676125

This is actually the first simulation of the vector, but I need 3 times this vector. One solution is to create 9 numbers, but VN is a vector of 9 elements:

    [1] 0.9439524 1.9539645 3.4676125 1.0070508 2.0258575 3.5145195 1.0460916 1.7469878 2.7939441

not 3 vectors of 3 elements. What I want is VN =

    [1] 0.9439524 1.0070508 1.0460916
    [2] 1.9539645 2.0258575 1.7469878
    [3] 3.4676125 3.5145195 2.7939441

so, VN are 3 vectors which I can subsequently use in other calculations, such as KN * VN. The solution that I have found is:

    set.seed(123)
    VN <- as.data.frame(t(matrix(rnorm(3 * length(V), V, VU), nrow = length(V))))

but in my opinion this is a rather cumbersome expression (which I need to repeat several times in different places with rather long variable names). Is there a simpler way in base R to produce random vectors? I would like to see something like:

    VN <- rnorm.vector(3, V, VU)
like image 276
JASC Avatar asked Jan 26 '23 23:01

JASC


1 Answers

We can use replicate

set.seed(123)
replicate(3, rnorm(3, V, VU))
#          [,1]     [,2]     [,3]
#[1,] 0.9439524 1.007051 1.046092
#[2,] 1.9539645 2.025858 1.746988
#[3,] 3.4676125 3.514519 2.793944

Or it could be

mapply(rnorm, n = 3, mean = V, sd = VU)
like image 147
akrun Avatar answered Feb 13 '23 16:02

akrun