0

I have something like that:

One       Two 
A,B,C       A 
A,C,        Z 
R,F,        K 
T           T  

And I would like to get in the 'Third' yes/no if 'Two' is contained in 'One'.

One       Two    Three
A,B,C       A     yes
A,C,        Z     no 
R,F,        K     no 
T           T     yes  

I know I can get it by using grepl, like that: grepl("A" , all$One) -> all&Three. But I have a few hundreds cases, so I am not able to write all those individual queries.
So how I should implement the whole 'Two' cell as a pattern in a greplfunction?

A. Suliman
  • 12,235
  • 5
  • 20
  • 34
K.M
  • 19
  • 3

2 Answers2

2

You can use stringr::str_detect

library(tidyverse)
df %>%
    mutate_if(is.factor, as.character) %>%
    mutate(Three = str_detect(One, Two))
#    One Two Three
#1 A,B,C   A  TRUE
#2  A,C,   Z FALSE
#3  R,F,   K FALSE
#4     T   T  TRUE

Sample data

df <- read.table(text  =
    "One       Two
A,B,C       A
A,C,        Z
R,F,        K
T           T", header = T)
Maurits Evers
  • 45,165
  • 4
  • 35
  • 59
2

You can use mapply():

all <- read.table(header=TRUE, stringsAsFactors = FALSE, text=
"One       Two 
A,B,C       A 
A,C,        Z 
R,F,        K 
T           T")
all$Three <- mapply(grepl, all$Two, all$One)
all
# > all
#     One Two Three
# 1 A,B,C   A  TRUE
# 2  A,C,   Z FALSE
# 3  R,F,   K FALSE
# 4     T   T  TRUE

If you really want "yes" or "no" as result, then you can do:

all$Three <- ifelse(mapply(grepl, all$Two, all$One), "yes", "no")

or (as commented by Rui Barradas, thx):

all$Three <- factor(mapply(grepl, all$Two, all$One), labels = c("no", "yes"))
jogo
  • 12,306
  • 11
  • 34
  • 41