Reputation: 53
N <- 10000 ; maxbound = 20
one_side_normal <- function(N) {
f <- numeric(N);
for (i in 1:N) {
X = rexp(1,rate=1);
uniform = runif(1);
while (uniform>exp((-X^2)+X) ){
X = rexp(1,rate=1);
uniform=runif(1);
}
f[i] <- X
}
return(f)
}
The above code samples from a one sided normal distribution(sample =10000) using the acceptance-rejection method. How would I loop this code to run 4 separate times for samples of 10,100,1000 & 10000?
Upvotes: 0
Views: 18
Reputation: 887048
We can use lapply
to loop over the N
values and apply the function. As there is only a single argument, we don't need any lambda function. It will return a list
lst1 <- lapply(c(10, 100, 1000, 10000), one_side_normal)
Another option is the classic for
loop. To store the output, we can create a NULL
list
of fixed length i.e length of the vector of 'N' values. Then, loop over the sequence of 'N', apply the function and assign (<-
) the output to the corresponding list
element with that index
nvec <- c(10, 100, 1000, 10000)
lst1 <- vector('list', length(nvec))
for(i in seq_along(nvec)) lst1[[i]] <- one_side_normal(nvec[[i]])
Upvotes: 1