-3

I have a vector of column like following

   a = "ASDRT" "GTYHE" "AQWER" QWERT"

And I have a dataframe like following

      ID.           Amount

   SDFGH.       45
   ASDRT.        67
   AQWER.      88
   TYUIIO.        543
   QWERT.        32

I want to match vector values with ID column of dataframe and if there is a match it will print 1 else 0

Desired output

      ID.         Amount.        Match
    SDFGH.       45.               0
   ASDRT.        67.               1
   AQWER.      88.                1
   TYUIIO.        543.             0
   QWERT.        32.              1

How can I do it in R ?

Neil
  • 7,937
  • 22
  • 87
  • 145

1 Answers1

0

We can remove the . at the end with sub, use %in% to get a logical vector, coerce it to binary with as.integer to create the 'Match' column

df1$Match <- as.integer(sub("\\.$", "", df1$ID) %in% a)
df1$Match
#[1] 0 1 1 0 1

Or another efficient option is stri_detect from stringi

library(stringi)
as.integer(stri_detect_regex(df1$ID, paste(a, collapse="|")))
akrun
  • 874,273
  • 37
  • 540
  • 662