Home > database >  Is there an R function that can replace data that contains certain characters?
Is there an R function that can replace data that contains certain characters?

Time:05-04

What I have is something like this:

Contact ID Number
Me@email 576489
You@memail 984601
072233498 256470
@email ---

I want to replace it so that anything containing an @ or a number is replaced entirely with simply "Yes" is that possible? So it would output something like this:

Contact ID Number
Yes Yes
Yes Yes
Yes Yes
Yes ---

CodePudding user response:

You can do:

df[] <- lapply(df, function(x) ifelse(grepl("@|\\d", x), "Yes", x))

df
#>   Contact ID Number
#> 1     Yes       Yes
#> 2     Yes       Yes
#> 3     Yes       Yes
#> 4     Yes       ---

Reproducible data

df <-  structure(list(Contact = c("Me@email", "You@memail", "072233498", 
"@email"), `ID Number` = c("576489", "984601", "256470", "---"
)), class = "data.frame", row.names = c(NA, -4L))

df
#>      Contact ID Number
#> 1   Me@email    576489
#> 2 You@memail    984601
#> 3  072233498    256470
#> 4     @email       ---

CodePudding user response:

str_replace(string, pattern, replacement) from the package "stringr"

str_replace(string, "@", "Yes")
  • Related