user20253433
user20253433

Reputation: 61

R: how to check if a vector is found in another vector of different length without using %in%

vector_1 = c(4,3,5,1,2)
vector_2 = c(3,1)

output:
[1] FALSE  TRUE FALSE  TRUE FALSE

how do I get the output just by using basic operators/loops without using the operator %in% or any functions in R?

Upvotes: 1

Views: 66

Answers (3)

jay.sf
jay.sf

Reputation: 72813

Without "functions" is a bit vague, since virtually anything in R is a function. Probably that's an assignment and a for loop is wanted.

res <- logical(length(vector_1))

for (i in seq_along(vector_1)) {
  for (j in seq_along(vector_2)) {
    if (vector_1[i] == vector_2[j])
    res[i] <- TRUE
  }
}

res
# [1] FALSE  TRUE FALSE  TRUE FALSE

However, that's not very R-ish where you rather want to do something like

apply(outer(vector_1, vector_2, `==`), 1, \(x) x[which.max(x)])
# [1] FALSE  TRUE FALSE  TRUE FALSE

Data:

vector_1 <- c(4, 3, 5, 1, 2)
vector_2 <- c(3, 1)

Upvotes: 1

Ric
Ric

Reputation: 5722

See match.fun(`%in%`)

match(vector_1,vector_2, nomatch = 0) > 0

Upvotes: 2

Shree
Shree

Reputation: 11140

One way with sapply() -

sapply(vector_1, function(x) any(x == vector_2))
[1] FALSE  TRUE FALSE  TRUE FALSE

Upvotes: 1

Related Questions