简体   繁体   中英

How to generate such random numbers in R

I want to generate bivariates in the following way. I have four lists with equal length n . I need to use the first two lists as means lists, and the latter two as variance lists, and generate normal bivariates.

For example n=2 , I have the lists as (1, 2) , (3, 4) , (5, 6) , (7, 8) , and I need c(rnorm(1, mean=1, sd=sqrt(5)), rnorm(1, mean=2, sd=sqrt(6)), rnorm(1, mean=3, sd=sqrt(7)), rnorm(1, mean=4, sd=sqrt(8)),ncol=2)

How can I do this in R in a more functional way?

Here is one way:

m <- 1:4
s <- 5:8
rnorm(n = 4, mean = m, sd = s)
[1]  4.599257  1.661132 16.987241  3.418957

This works because, like many R functions, rnorm() is 'vectorized', meaning that it allows you to call it once with vectors as arguments, rather than many times in a loop that iterates through the elements of the vectors.

Your main task, then, is to convert the 'lists' in which you've got your arguments right now into vectors that can be passed to rnorm() .

NOTE : If you want to produce more than one -- lets say 3 -- random variate for each mean/sd combination, rnorm(n=rep(3,4), mean=m, sd=s) will not work. You'll have to either: (a) repeat elements of the m and s vectors like so rnorm(n=3*4, mean=rep(m, each=3), sd=rep(s, each=3)) ; or (b) use mapply() as described in DWin's answer.

I'm taking you at your word that you have a list, ie an Rlist:

plist <- list( a=list(1, 2), b=list(3, 4), c=list(5, 6), d=list(7, 8))
 means <-plist[c("a","b")]  # or you could use means <- plist[1:2]
 vars <- plist[c("c","d")]
 mapply(rnorm, n=rep(1,4), unlist(means), unlist(vars))
#[1]  3.9382147  1.0502025  0.9554021 -7.3591917

You used the term bivariate. Did you really want to have x,y pairs that had a specific correlation?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM