[R] lapply to apply a function using a vector

Dan Davison davison at stats.ox.ac.uk
Wed Feb 17 18:51:50 CET 2010


Flana <flana.bristo <at> gmail.com> writes:

> 
> Hi,
> 
> First, thank you all for your help.
> 
> Here is my problem (simplified):
> 
> Say I have a list:
> a=list(matrix(50,nrow=5,ncol=5),
>  matrix(25,nrow=5,ncol=5),
>  matrix(10,nrow=5,ncol=5))
> 
> I'd like to use rbinom with a different probability for each matrix. I
> tried:
> 
> b=c(.8,.1,.9)
> brep=rep(b,each=25)
> lapply(a,function(a) rbinom(25,a,brep))
> 
> but that doesn't work-- it just uses the first value of b rather than
> applying it over that list.

Seeing as you want to index in to both the size and prob arguments of
rbinom, you can use mapply, rather than lapply:

mapply(function(size, prob)
       matrix(rbinom(25, size=size, prob=prob), nrow=5, ncol=5),
       c(50,25,10), c(.8,.1,.9), SIMPLIFY=FALSE)

An lapply equivalent would have to use an explicit index variable, e.g.

lapply(1:3, function(i) matrix(rbinom(25, size=a[[i]], prob=b[i]), nrow=5))

However, it may be that neither of these are the most efficient way to
do this, as they involve calling rbinom multiple times. For just 3
different parameter sets (prob and size) that's unlikely to be a
problem, but if you were simulating for a large number of parameter sets 
then you might want to consider calling rbinom once and subsequently
unpacking the results, e.g.

size <- rep(c(50,25,10), each=25)
prob <- rep(c(.8,.1,.9), each=25)
x <- rbinom(25*3, size=size, prob=prob)
lapply(split(x, rep(1:3, each=25)), matrix, nrow=5)

Dan


> what I am currently doing is:
> c=list()
> for (i in 1:3){c[[i]]=rbinom(25,a[[i]],b[i])}



More information about the R-help mailing list