Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

splitting a list into two lists based on odd/even indices

Tags:

list

r

I have a list of the form:

dat[[1]], dat[[2]], ..., dat[[n]]

and I would like to obtain instead two separate lists, one containing dat with odd indices and the other one with even indices, i.e.:

new_dat_odd <- dat[[1]], dat[[3]], dat[[5]], ...
new_dat_even <- dat[[2]], dat[[4]], dat[[6]], ...

In trying to do this, my main issue is I can't find how to refer to the indices of a list in R.

Thank you for any suggestions.

like image 485
Neodyme Avatar asked Dec 11 '22 05:12

Neodyme


1 Answers

1) If L is the list then we can use this code where we note that 1:2 is recycled as needed:

s <- split(L, 1:2)

1a) The above works whether the list is even or odd length but as per the comment if odd it gives a warning. The followingi modification gives the same answer but gives no warning:

s <- split(L, rep(1:2, length = length(L)))

In either of the above s[[1]] and s[[2]] are the two lists. For example,

> L <- as.list(1:10)
> str(split(L, 1:2))
List of 2
 $ 1:List of 5
  ..$ : int 1
  ..$ : int 3
  ..$ : int 5
  ..$ : int 7
  ..$ : int 9
 $ 2:List of 5
  ..$ : int 2
  ..$ : int 4
  ..$ : int 6
  ..$ : int 8
  ..$ : int 10

2) Here is another way:

is.odd <- rep(c(TRUE, FALSE), length = length(L))
list(odd = L[is.odd], even = L[!is.odd])

Update Added 1a and 2.

like image 134
G. Grothendieck Avatar answered Jan 15 '23 16:01

G. Grothendieck