CreateNew Column with Match other two column status

Could someone please help the below problem..
i wanted to create new Column with match status.

test <- tibble(Q3 = c("CH","EN", "NA", "FR", "IN"),
               Q8 = c("NA,ch", "AA,DL", "NA,DL", "na,DL", "NA,DL"))

 test1<-test %>% 
    mutate(status= if_else(grepl(Q3, Q8, ignore.case = TRUE), "TestedMatch", Q3))

Col Q8 contain in Q3

i expect 1st row and 3rd row should have TRUE

Here's a solution using str_detect().

The error is because you were passing grepl() a vector. The result is "TestedMatch" and not TRUE, because you've specified the string in the case that they match.

Note that the arguments for str_detect() are not in the same order as those for grepl().

suppressPackageStartupMessages(library(tidyverse))
test <- tibble(
  Q3 = c("CH", "EN", "NA", "FR", "IN"),
  Q8 = c("NA,ch", "AA,DL", "NA,DL", "na,DL", "NA,DL")
)

test1 <- test %>%
  mutate(status = if_else(str_detect(tolower(Q8), tolower(Q3)), "TestedMatch", Q3))

test1
#> # A tibble: 5 x 3
#>   Q3    Q8    status     
#>   <chr> <chr> <chr>      
#> 1 CH    NA,ch TestedMatch
#> 2 EN    AA,DL EN         
#> 3 NA    NA,DL TestedMatch
#> 4 FR    na,DL FR         
#> 5 IN    NA,DL IN

Created on 2019-06-26 by the reprex package (v0.3.0)

this is exactly i need,

by the by do you know is there any option using Puur or dplyr

if_else() is in dplyr. If you're looking for string matching without stringr, then I'm sure you can do it using only base R code.

looking for equivalent str_detect() in base

If you want to use base R grepl() you just have to add rowwise() to your code

library(tidyverse)

test <- tibble(Q3 = c("CH","EN", "NA", "FR", "IN"),
               Q8 = c("NA,ch", "AA,DL", "NA,DL", "na,DL", "NA,DL"))

test1 <- test %>% 
    rowwise() %>% 
    mutate(status= if_else(grepl(Q3, Q8, ignore.case = TRUE), "TestedMatch", Q3))

test1
#> Source: local data frame [5 x 3]
#> Groups: <by row>
#> 
#> # A tibble: 5 x 3
#>   Q3    Q8    status     
#>   <chr> <chr> <chr>      
#> 1 CH    NA,ch TestedMatch
#> 2 EN    AA,DL EN         
#> 3 NA    NA,DL TestedMatch
#> 4 FR    na,DL FR         
#> 5 IN    NA,DL IN
1 Like

Complete base R solution, without any tidyverse function:

test <- data.frame(Q3 = c("CH", "EN", "NA", "FR", "IN"),
                   Q8 = c("NA,ch", "AA,DL", "NA,DL", "na,DL", "NA,DL"),
                   stringsAsFactors = FALSE)

within(test,
       score <- ifelse(test = mapply(FUN = grepl,
                                       pattern = Q3,
                                       x = Q8,
                                       ignore.case = TRUE),
                         yes = "TestedMatch",
                         no = Q3))
#>   Q3    Q8       score
#> 1 CH NA,ch TestedMatch
#> 2 EN AA,DL          EN
#> 3 NA NA,DL TestedMatch
#> 4 FR na,DL          FR
#> 5 IN NA,DL          IN
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.