[R] Question: Form a new list with the index replicated equal to the number of elements in that index

Peter Dalgaard pdalgd at gmail.com
Mon Sep 13 22:20:10 CEST 2010


On 09/13/2010 08:41 PM, Sunny Srivastava wrote:
> Dear R-Helpers,
> I have a list l1 like:
> 
> l1[[1]]
> a b c
> 
> l1[[2]]
> d
> 
> l1[[3]]
> e f
> 
> I want an output res like:
> 
> res[[1]]
> 1 1 1
> 
> res[[2]]
> 2
> 
> res[[3]]
> 3 3
> 
> Essentially, I want to replicate each index equal to the number of elements
> present in that index.
> 
> Below is what I do to accomplish this:
> 
> l1 <- list(c("a", "b", "c"), "d", c("e", "f"))
> res <- mapply(rep, seq_along(l1),times=(lapply(l1, length)))
> 
> Is there a more elegant way of doing this (possibly using one (l/m)apply
> function)?

Don't know about elegance, but how about

lapply(seq_along(l1), function(i)rep(i, length(l1[[j]])) )

-- 
Peter Dalgaard
Center for Statistics, Copenhagen Business School
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list