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,923
  • 5
  • 24
  • 37
K.M
  • 19
  • 3
  • Please make your example reproducible! https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – jogo Aug 06 '18 at 09:20
  • `all$Three <- mapply(grepl, all$Two, all$One)` – jogo Aug 06 '18 at 09:22

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
  • 49,617
  • 4
  • 47
  • 68
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,469
  • 11
  • 37
  • 42