Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a list of named lists from three vectors in R

Tags:

r

I'm trying to combine three vectors into a list of lists, with one vector being the indexes for the list.

Given

names<-c("a","b","c","d")
id1<-c(1,1,2,2)
id2<-c(3,4,5,6)

I would like to build a list looking like this:

mylist <- list("a" = list(1,3), "b" = list(1,4), "c" = list(2,5), "d" = list(2,6))
like image 984
Micael E Avatar asked Dec 20 '25 02:12

Micael E


1 Answers

I think you are looking for Map

l <- Map(list, id1, id2) # thanks to @thelatemail for suggested improvement
names(l) <- names
identical(mylist, l)
# TRUE
like image 147
konvas Avatar answered Dec 22 '25 19:12

konvas



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!