Hanbo
Hanbo

Reputation: 161

Indexing table in [R]

I have a vector:

a = c(1, 3, 2, 2, 4, 1, 1, NA)

I want to generate something like:

[["1"]]
1, 6, 7
[["2"]]
3, 4
[["3"]]
2
[["5"]]
5

Mapping from value to index. Any help!

Upvotes: 1

Views: 157

Answers (3)

akrun
akrun

Reputation: 887148

Here is another option with unstack

unstack(list(i = seq_along(a), a), i ~ a)
#$`1`
#[1] 1 6 7

#$`2`
#[1] 3 4

#$`3`
#[1] 2

#$`4`
#[1] 5

Upvotes: 1

thelatemail
thelatemail

Reputation: 93813

This is a split operation on the indexes of a:

split(seq_along(a), a)

#$`1`
#[1] 1 6 7
#
#$`2`
#[1] 3 4
#
#$`3`
#[1] 2
# 
#$`4`
#[1] 5

Upvotes: 4

IceCreamToucan
IceCreamToucan

Reputation: 28685

setNames(lapply(unique(a), function(x) which(x == a)), unique(a))

# $`1`
# [1] 1 6 7
# 
# $`3`
# [1] 2
# 
# $`2`
# [1] 3 4
# 
# $`4`
# [1] 5
# 
# $<NA>
# integer(0)

This is slightly shorter using tidyverse

library(tidyverse)
map(unique(a) %>% setNames(.,.), ~which(.x == a))

Upvotes: 2

Related Questions