0

I have a vector like so:

foo = c("A", "B", "C", "D")

And I want a vector of selected index numbers, which I imagined I could do like so:

which(foo == c("A", "B", "D"))

But apparently this only works if the lengths of the two vectors are multiples, as otherwise you get an incomplete result followed by a warning message:

"longer object length is not a multiple of shorter object length".

So how do I get what I'm after, which is "1 2 4"?

Leonardo
  • 2,439
  • 33
  • 17
  • 31

2 Answers2

2

Use match:

match(c('A', 'B', 'C'), foo)
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
1

Using %in% is one option here:

foo <- c("A", "B", "C", "D")
x <- c("A", "B", "D")
c(1:4)[foo %in% x]    # [1] 1 2 4

The quantity foo %in% x returns a logical vector which can then be used to subset the indices you want to see.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360