Reanimation
Reanimation

Reputation: 3336

Compare 2 Vectors of unknown length to find a common value? - R

How do you compare two Vectors in R, and find the last common "TRUE" value along the elements?

It's a bit hard to explain, so here's an example:

  Element:  [1]   [2]   [3]   [4]   [5]    [6]    [7]    [8]  [9]   [10]
  vec1 <- TRUE, TRUE, TRUE, TRUE, TRUE,  TRUE,  TRUE, FALSE,  NA, FALSE,
  vec2 <- TRUE, TRUE, TRUE, TRUE,   NA, FALSE, FALSE,    NA,  NA,    NA,

How can I compare vec1 and vec2 to find that Element 4 is the last common TRUE they share? and assuming the vectors are not always of the same length?

I hope this makes sense. Thanks in advance.

Upvotes: 0

Views: 252

Answers (3)

twin
twin

Reputation: 1669

l <- min(length(vec1), length(vec2))
tail(which((vec1[1:l] == vec2[1:l])), 1)

Upvotes: 1

Matt Weller
Matt Weller

Reputation: 2754

The bits of interest for your example are which and intersect. Here is a reproducible example below.

vec1 = sample(c(TRUE,FALSE),10, replace=TRUE)
vec2 = sample(c(TRUE,FALSE),10, replace=TRUE)
max(intersect(which(vec1), which(vec2)))

Upvotes: 1

Tyler Rinker
Tyler Rinker

Reputation: 109864

Here's one approach because a logical value (F=0 and T=1) when summed that adds to 2 means you had 2 TRUE. So we simply add the two vectors, use which to find the indices of those == to 2 and then take the last one with tail:

tail(which(vec1 + vec2 == 2), 1)

Upvotes: 0

Related Questions