How to generate random samples from different statistical distributions using parameters as a list in R?

R ProgrammingServer Side ProgrammingProgramming

To generate random samples from statistical distributions, we use functions like rnorm, rbinom, rexp, rpois for the corresponding distribution based on their names. Using these functions, we can pass their parameters as an argument inside the function. But if we have the parameters saved as a list then generation of random sample is not straight forward, for this we need to use do.call function.

Examples

parameters1<-list(mean=1,sd=0.5)
do.call(rnorm,c(list(n=50),parameters1))

Output

[1] 0.7544844 -0.1545844 1.5028693 0.6453996 0.6559957 1.5127857
[7]  0.8576135 0.3896411 1.0906517 0.9305543 1.0028821 1.1926402
[13] 0.8146700 1.3221883 0.8897567 1.1658910 1.5484195 1.2175907
[19] 0.8370342 1.5744038 1.4967519 1.2741985 1.1193659 0.6860470
[25] 1.6803262 0.6998702 2.0936665 1.7663053 0.8821498 0.4867895
[31] 0.6447967 1.1284419 0.8766541 0.8262287 0.5241907 0.9774861
[37] 0.6075478 0.1660290 0.8098867 1.4594983 0.7123265 1.3039822
[43] 0.1910586 0.9722190 1.2597036 1.1505767 1.0528381 0.6796470
[49] 0.5751478 0.4879356

Example

parameters2 <-list(size=20,p=0.5)
do.call(rbinom,c(list(n=50),parameters2))

Output

[1] 10 7 10 8 10 9 15 9 8 11 8 14 10 8 11 15 11 10 9 12 8 8 13 9 9
[26] 12 8 5 9 10 10 9 12 10 10 14 12 8 9 14 10 12 9 12 10 13 8 9 7 8

Example

parameters3 <-list(lambda=5)
do.call(rpois,c(list(n=50),parameters3))

Output

[1] 10 4 6 7 2 3 4 2 2 11 10 3 8 5 4 5 6 2 4 6 4 7 3 5 4
[26] 3 9 4 5 1 5 6 5 4 8 6 4 4 3 7 9 5 4 12 3 5 2 5 2 3

Example

parameters4 <-list(min=2,max=10)
do.call(runif,c(list(n=50),parameters4))

Output

[1] 4.263943 6.670979 7.853661 3.324167 8.931742 7.668593 8.083196 3.176673
[9] 4.864456 7.386660 6.190581 4.798414 3.924246 2.465534 3.892958 9.120623
[17] 8.494619 7.980131 3.239294 2.997937 9.797806 5.489040 5.712133 3.322385
[25] 6.679492 4.166224 3.840775 7.529663 4.262819 8.483185 2.751333 8.576241
[33] 5.419426 8.047098 7.299084 5.556219 7.017169 2.003723 3.737948 7.638978
[41] 3.721332 8.511470 4.462111 7.501941 9.461449 2.926237 3.021646 7.425791
[49] 5.431589 8.675208

Example

parameters5 <-list(rate=1)
do.call(rexp,c(list(n=50),parameters5))

Output

[1] 0.048859236 2.470484229 0.034337427 0.573854705 1.107571484 1.158912960
[7] 0.841547703 2.359008139 1.154964259 1.810404878 0.072107441 0.007897424
[13] 0.236585886 2.399940448 0.274251057 1.760241609 0.736572850 0.630162990
[19] 0.897717278 1.151831293 0.941598348 2.968427598 0.037609847 0.358026831
[25] 0.017693759 0.904697679 0.309862433 0.632956278 3.036563054 0.478063371
[31] 1.088025155 0.658501647 0.071082783 0.791328635 0.601896424 2.545756658
[37] 0.664215548 0.800567470 0.506220199 0.056468316 0.604476434 1.233841599
[43] 1.003536777 2.025803985 0.138765325 0.367169829 0.331470285 0.059784917
[49] 0.019685799 3.500006681
raja
Published on 24-Aug-2020 11:44:53
Advertisements