0
votes

I'm new to the forum and to r, so please forgive the sloppy code.

In short, I am trying to get a normal distribution to iteratively use the parameters drawn from two lists for use in a For Loop that generates a 30x10000 matrix of random samples using these parameters.

The first list (List1) is a collection of numeric vectors. The second list (List2) has corresponding values I would like to use for the standard deviation argument in rnorm: i.e. vector 1 from List1's standard deviation is Value1 in List2.

set.seed(1500) #set up random gen
var1 = rnorm(1:1000, mean = #mean of vector(i) from list1, sd = #value(i) from List2)
sample(var1,size=1)
X = matrix(ncol = 30, nrow = 10000)
for(j in 1:length(var1)){ #simulates data using parameters set by rnorm var1 function
    for(i in 1:10000){
    X[i.j] = sample(var1,1)
  }
}

Here's the original post where this code is inspired from.

Cheers!

1

1 Answers

0
votes

It seems mapply() would help you:

# First let's turn the list1 into means.
dist.means = lapply(list1,mean) 

Lapply is a way to execute a function for every element in a list. Mapply works in a very similar way but uses multiples lists.

samples = mapply(rnorm, 30*10000, dist.means, list2,SIMPLIFY=F)

A little bit more explanation: mapply() runs rnorm() multiple times. In the first attempt, it runs using the first element of first list as the first argument, the first element of second list as second argument, etc. So in our case it will run rnorm( 30*10000, dist.means[[1]], list2[[1]] ) then rnorm( 30*10000, dist.means[[2]], list2[[2]] ) and store the output in a list.

Note that I use a small trick here. The first list is a single number 30*10000. When you give list of different sizes to mapply it recycles the shorter one, i.e. it repeats the shorter lists until it has the same length of the longer lists.

Hope that helps