student_R123
student_R123

Reputation: 1002

generate random number with varying parameters using lapply in R

I need to generate random numbers (binomial) with varying parameters. I am trying to do that using lapply function.

This is my code so far:

lst1 <- list(n=c(10,20), size=c(100,200), q=c(0.1,0.2)) #list of variables

lapply(lst1, function(x) {
  rbinom(x[1],x[2],x[3])
})

Seems there is an error.

Then I tried this way as well,

lapply(lst1, function(x) {
  rbinom(x$n,x$size,x$q)
})

Still I am getting an error. Can anyone help me to figure out the error ?

Thank you.

Upvotes: 2

Views: 476

Answers (2)

akrun
akrun

Reputation: 887851

Or use pmap from purrr after making matching names of the list with the arguments of the function.

names(formals(rbinom))
#[1] "n"    "size" "prob"

Here the 'q' can be renamed as 'prob'

library(purrr)
names(lst1)[3] <- 'prob'
pmap(lst1, rbinom)
#[[1]]
# [1] 13  9 12 19 11  8 14 13 16  7

#[[2]]
# [1] 42 52 37 48 41 33 34 31 47 41 41 40 39 42 41 41 52 47 42 49

Upvotes: 2

Karolis Koncevičius
Karolis Koncevičius

Reputation: 9656

Better to use Map instead of lapply when the function needs to get a different set of parameters each time:

> Map(rbinom, lst1$n, lst1$size, lst1$q)
[[1]]
 [1] 15  7  8 12  9 11  4  9 12  7

[[2]]
 [1] 47 40 37 54 40 39 39 43 50 33 34 37 42 31 26 34 31 38 43 43

With lapply you could do it like this:

lapply(1:2, function(ind) rbinom(lst1$n[ind], lst1$size[ind], lst1$q[ind]))
[[1]]
 [1] 10 18  7  9  9 18  7  8  8 10

[[2]]
 [1] 46 42 44 37 38 40 52 44 42 38 40 35 41 46 44 38 41 32 61 33

Upvotes: 6

Related Questions