0

Can I associate an index to a vector that is maintained and that I can retrieve by a second vector?

V1<-c("a", "b", "c", "d", "e", "f")

I want to associate an index something similar to:

"a" "b" "c" "d" "e" "f"
 1   2   3   4   5   6

Then by a second vector

V2<-c("b", "c", "f")

I should get integers 2, 3, 6

I know I can create a data frame with two columns ID=V1 and ixd= 1:length(V1)and subset by V2

I am wondering if there is a faster way

Al14
  • 1,734
  • 6
  • 32
  • 55

2 Answers2

1

You can do a named vector, i.e.

v1 <- setNames(seq(6), letters[1:6])

#then,

v1[names(v1) %in% c('b', 'c', 'f') ]
#b c f 
#2 3 6 

Note that while a named vector also has names for its values, it is still numeric

Or as @jogo suggests, simply

v1[c('b', 'c', 'f')]
#b c f 
#2 3 6 
Sotos
  • 51,121
  • 6
  • 32
  • 66
1

I wanted to provide an alternative way:

V1 <- 1:6 names(V1) <- letters[1:6] # Attach names to your list V2 <- letters[seq(2,6,2)] # c("b","d","f") V1[V2]

This gives me

b d f
2 4 6
CPak
  • 13,260
  • 3
  • 30
  • 48
  • Output-wise, nothing. But some code can be easier to read/understand than others. For instance, I show that you can attach names to a list after declaring the list (don't need to do it concurrent). And that you can index a list by name directly. Perhaps these are useful to the OP. – CPak Jun 08 '17 at 14:55