[R] reorder a list

Greg Snow 538280 at gmail.com
Tue Jul 8 19:41:18 CEST 2014


Here is another approach inspired by Jim's answer:

> names(A1) <- paste0(seq_along(A1),'.')
> tmp <- unlist(A1)
> split( rep( seq_along(A1), sapply(A1,length) ), as.numeric(sub('\\..+$','',tmp)) )
$`1`
[1] 1

$`2`
[1] 1 2

$`3`
[1] 1

$`4`
[1] 1 2 4

$`5`
[1] 2 4

$`13`
[1] 4

$`23`
[1] 3

On Tue, Jul 8, 2014 at 11:10 AM, jim holtman <jholtman at gmail.com> wrote:
> Try this:
>
>> A1<-list(c(1:4),c(2,4,5),23,c(4,5,13))
>>
>> # unlist with the list number
>> result <- do.call(rbind, sapply(seq(length(A1)), function(.indx){
> +     cbind(value = A1[[.indx]], index = .indx)
> + }))
>>
>> ans <- split(result[, 2], result[, 1])
>> ans
> $`1`
> [1] 1
>
> $`2`
> [1] 1 2
>
> $`3`
> [1] 1
>
> $`4`
> [1] 1 2 4
>
> $`5`
> [1] 2 4
>
> $`13`
> [1] 4
>
> $`23`
> [1] 3
>
>
>
> Jim Holtman
> Data Munger Guru
>
> What is the problem that you are trying to solve?
> Tell me what you want to do, not how you want to do it.
>
>
> On Tue, Jul 8, 2014 at 12:39 PM, 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.
>>
>
>         [[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.



-- 
Gregory (Greg) L. Snow Ph.D.
538280 at gmail.com



More information about the R-help mailing list