Reputation:
I am trying to run a simulation that creates two independent normal distributions from different n-counts, means, and standard deviations. For example, n-counts from 100 to 1000, means from 0 to 100, and standard deviations from 1 to 10, where each element from each vector combines with every other element of the other two vectors, like so: 100, 0, 1; 100, 0, 2; 100, 0, 3;...100, 1, 1; 100, 1, 2; 100, 1, 3;...999, 0, 1; etc.
I first tried to create three vectors that had these numbers:
ncount <- 100:1000
means <- 0:100
std <- 1:10
I also wrote a rudimentary function like so:
distr <- function(count, mean, stddev) {
distr1 <- rnorm(count1, mean1, stddev1)
hist(distr1)
}
At this point, I'm stuck (mostly because of not knowing) what R can do to cycle through each of the values in these vectors to produce the different distributions. Suggestions?
Upvotes: 1
Views: 36
Reputation: 10167
While @Marat Talipov's answer is ideal from many respects,
don't forget that you can also use nested for
loops, as in:
for(ncount in 100:1000)
for(means in 0:100)
for(std in 1:10)
distr(ncount,means,std)
Upvotes: 0
Reputation: 13304
You can use expand.grid
, which will create all combinations of ncount/means/std, and Vectorize
, which will 'teach' your function to treat input arguments in a row-wise manner:
ncount <- 100:101
means <- 0:2
std <- 1:3
distr <- function(count, mean, stddev) {
distr1 <- rnorm(count, mean, stddev)
hist(distr1)
}
d <- expand.grid(ncount=ncount,means=means,std=std)
Vectorize(distr)(d$ncount,d$means,d$std)
Upvotes: 1