Search code examples
rfor-looprep

Repeat function on R


So my issue is the following: I'm trying to put together a list where each entry is a vector of multiple values simulated under a negative binomial distribution. I'm trying to use this code:

> test <- list()
> for(i in 1:100) {
+   test[[i]] <- rep(rnbinom(n=1000, size=36, prob=0.4), times = i, each =1)
+ }

However, I´m getting a list where the entries increase in size. Something like this:

int [1:1000] 33 82 44 33 58 45 63 ...
int [1:2000] 51 48 28 76 49 71 52 ...
int [1:3000] 59 53 65 72 38 41 48 ...

And so forth. In this case, I want every entry to have the same size (n=1000) but something is not quite right. Any help would be appreciated, thanks!


Solution

  • You're actually looking for replicate:

    replicate(3,rnbinom(n=10, size=36, prob=0.4),F)
    # [[1]]
    # [1] 67 31 84 57 61 62 49 62 57 54
    # 
    # [[2]]
    # [1] 53 45 39 54 66 51 41 56 42 68
    # 
    # [[3]]
    # [1] 62 57 58 43 35 50 47 51 62 50