[R] reorder a list
Greg Snow
538280 at gmail.com
Tue Jul 8 19:11:05 CEST 2014
Here is one approach that gives almost the same answer as your example:
> A1<-list(c(1:4),c(2,4,5),23,c(4,5,13))
>
> A2 <- sort(unique(unlist(A1)))
> names(A2) <- A2
> sapply(A2, function(x) which( sapply(A1, function(y) x %in% y) ),
+ simplify=FALSE, USE.NAMES=TRUE )
$`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
If you want the `23` to be in the 23rd element of the list (with empty
values before it) then just change A2 to be a vector from 1 to the
largest value
On Tue, Jul 8, 2014 at 10: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.
--
Gregory (Greg) L. Snow Ph.D.
538280 at gmail.com
More information about the R-help
mailing list