[R] reorder a list

William Dunlap wdunlap at tibco.com
Tue Jul 8 21:11:09 CEST 2014


f <- function (x) {
    lengths <- vapply(x, FUN = length, FUN.VALUE = 0L)
    split(rep(seq_along(x), lengths), unlist(x, use.names = FALSE))
}
f(A1) # gives about what you want (has, e.g., name 23, not position
23, in output)
Bill Dunlap
TIBCO Software
wdunlap tibco.com


On Tue, Jul 8, 2014 at 9:39 AM, Lorenzo Alfieri <alfios17 at hotmail.com> wrote:
> Hi,
> I'm trying to find a way to reorder the elements of a list.
> Let's say I have a list like this:
> A1<-list(c(1:4),c(2,4,5),23,c(4,5,13))
>
>> A1
> [[1]]
> [1] 1 2 3 4
>
> [[2]]
> [1] 2 4 5
>
> [[3]]
> [1] 23
>
> [[4]]
> [1]  4  5 13
>
> All the elements included in it are values, while each sublist is a time index
> Now, I'd like to reorder the list (without looping) so to obtain one sublist for each value, which include all the time indices where each value appears.
> In other words, the result should look like this:
>>A2
> [[1]]
> [1] 1
>
> [[2]]
> [1] 1 2    #because value "2" appears in the time index [[1]] and [[2]] of A1
>
> [[3]]
> [1] 1
>
> [[4]]
> [1] 1 2 4
>
> [[5]]
> [1] 2 4
>
> [[13]]
> [1] 4
>
> [[23]]
> [1] 3
>
> Any suggestion?
> Thanks
> Alfio
>
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org 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