Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create bijection between two lists?

Tags:

r

Good afternoon !

I'm wanting to transform a list like the following :

list_1= list(c(1,30,25),c(51,70),c(102,130,125))

to be :

list_2=list(c(1,2,3),c(4,5),c(6,7,8))

I know that we can retrieve list_1 lengths with :

lengths(list_1)
3 2 3 

The list_2 represent indices of list_1 elements ( in case we unlist them ) .

I hope my question is clear , thank you for help in advance !

like image 342
Tou Mou Avatar asked Feb 28 '26 06:02

Tou Mou


2 Answers

Using split.

ll <- lengths(list_1)
unname(split(seq(unlist(list_1)), rep(seq(ll), ll)))
# [[1]]
# [1] 1 2 3
# 
# [[2]]
# [1] 4 5
# 
# [[3]]
# [1] 6 7 8
like image 106
jay.sf Avatar answered Mar 02 '26 21:03

jay.sf


An option with relist

relist(seq_along(unlist(list_1)), skeleton = list_1)
#[[1]]
#[1] 1 2 3

#[[2]]
#[1] 4 5

#[[3]]
#[1] 6 7 8
like image 35
akrun Avatar answered Mar 02 '26 21:03

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!