0

Dataframe:

     A  B 
1    a  c
2    x  x
3    t  q
4    l  l
5    w  y
6    b  b

I want to add a column that detects a match or mismatch:

     A  B  C 
1    a  c  miss
2    x  x  match
3    t  q  miss
4    l  l  match
5    w  y  miss
6    b  b  match
cAB
  • 5
  • 2

3 Answers3

1

A base R option

transform(
  df,
  C = c("miss","match")[(A==B)+1]
)

giving

  A B     C
1 a c  miss
2 x x match
3 t q  miss
4 l l match
5 w y  miss
6 b b match

Data

> dput(df)
structure(list(A = c("a", "x", "t", "l", "w", "b"), B = c("c", 
"x", "q", "l", "y", "b")), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
0
> dd %>% rowwise() %>% mutate(match = case_when(A == B ~ 'match', TRUE ~ 'miss'))
# A tibble: 6 x 3
# Rowwise: 
  A     B     match
  <chr> <chr> <chr>
1 a     c     miss 
2 x     x     match
3 t     q     miss 
4 l     l     match
5 w     y     miss 
6 b     b     match
> dd
# A tibble: 6 x 2
  A     B    
  <chr> <chr>
1 a     c    
2 x     x    
3 t     q    
4 l     l    
5 w     y    
6 b     b    
> 
Karthik S
  • 11,348
  • 2
  • 11
  • 25
0

A base R option with indexing (Althought @ThomasIsCoding is a more pro solution):

#Code
index <- df$A==df$B
df$C <- 'miss'
df$C[index]<-'match'

Output:

df
  A B     C
1 a c  miss
2 x x match
3 t q  miss
4 l l match
5 w y  miss
6 b b match

Some data used:

#Data
df <- structure(list(A = c("a", "x", "t", "l", "w", "b"), B = c("c", 
"x", "q", "l", "y", "b")), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6"))
Duck
  • 39,058
  • 13
  • 42
  • 84