What's another way to do column %in% vector?

From below code, mutate.(matched = a %in% vector_b) is in question.

library(tidytable)

df_a = data.frame(a = round(rnorm(2)))
df_b = data.frame(b = round(rnorm(2)))
vector_b = df_b |> pull.()

myfunction = function(df_matched, df_a, a, vector_b) {
  
  df_matched = df_a |>
    mutate.(matched = a %in% vector_b)
  
  return(df_matched)
}

df_matched = myfunction(df_matched, df_a, b, vector_b)

df_matched |> count.(matched)
# A tidytable: 2 × 2
#  matched     N
#  <lgl>   <int>
#1 FALSE       1
#2 TRUE        1

I was just wondering if there is another way to achieve the same thing as mutate.(matched = a %in% vector_b) without using %in%.

sure, you can use is.element()
e.g.:

is.element(1:2, 1:10)
[1] TRUE TRUE

is.element(-2:-1, 1:10)
[1] FALSE FALSE

if you look at the code for both is.element, and %in% they are both effectively wrapping the match function.

> is.element
function (el, set) 
match(el, set, 0L) > 0L
> `%in%`
function (x, table) 
match(x, table, nomatch = 0L) > 0L

Therefore using match more directly is an option.
However, I would generally just use %in% because its eminently more readable to me.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.