Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return list containing indices of each element in a vector

Tags:

r

I have a vector in R containing repetitive elements

a<-c("A","A","A","B","B","C","A")

And I would like to know the most efficient way to transform it in a list where each element is the key, and its positions in the original vector are the values:

l<-list(A=c(1,2,3,7),B=c(4,5),C=c(6))
l
$A
[1] 1 2 3 7
$B
[1] 4 5
$C
[1] 6
like image 597
Federico Giorgi Avatar asked Mar 24 '23 12:03

Federico Giorgi


1 Answers

split(seq_along(a), a)
# $A
# [1] 1 2 3 7
# 
# $B
# [1] 4 5
# 
# $C
# [1] 6
like image 110
flodel Avatar answered Apr 24 '23 18:04

flodel