[R] how to reverse a list
Gabor Grothendieck
ggrothendieck at gmail.com
Thu Apr 12 00:40:55 CEST 2007
Here is a minor shortening of that solution:
tapply(t0, unlist(t0), names)
On 4/11/07, rolf at math.unb.ca <rolf at math.unb.ca> wrote:
> Weiwei Shi wrote:
>
> > I am wondering if there is a quick way to "reverse" a list like this:
> >
> > t0 <- list(a=1, b=1, c=2, d=1)
> >
> > reverst t0 to t1
> >
> > > t1
> > $`1`
> > [1] "a" "b" "d"
> >
> > $`2`
> > [1] "c"
>
> t1 <- tapply(unlist(t0),unlist(t0),function(x){names(x)})
>
> works for your example. Not clear how ``general'' an answer
> you want.
>
> If the entries of your list are not scalars, then the problem is much
> harder I think. (And may not even be well posed.) But then you
> should be using a *vector*, not a list.
>
> Don't use a chainsaw when you need a fretsaw.
>
> cheers,
>
> Rolf Turner
> rolf at math.unb.ca
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list