1

I have two data frames, I was wondering how could I create a new column in the data frame "a" that indicates when theres a match with b?

data:

a <- c("123","123","321","321", "213")
a <- data.frame(a)

b <- c("123", "213")
b <- data.frame(b)

Result:

      Match
123    Yes
123    Yes
321    No
321    No
213    Yes
Xin
  • 666
  • 4
  • 16

1 Answers1

0

An option is %in% to create a logical vector in 'a' based on the elements in 'b', then change it to numeric index (+ 1), use that index to change the values to 'No', 'Yes'

data.frame(Match = c("No", "Yes")[(a$a %in% b$b) +1])
#  Match
#1   Yes
#2   Yes
#3    No
#4    No
#5   Yes

data.frame doesn't allow for duplicate row names, so if we need the original column from 'a', create as a column instead. of row names

cbind(a, Match = c("No", "Yes")[(a$a %in% b$b) +1])
akrun
  • 874,273
  • 37
  • 540
  • 662