R delete value from column if it does not contain itself in value from another column

iiaawaak

I have a dataframe in R that looks like this:

genus species
Vulgatibacter Echinacea sp.
NA Planctomyces
Holophaga Geothrix sp.

And I want to delete values from column species if the value from genus does not contain in species. I want to have this:

genus species
Vulgatibacter Echinacea sp.
NA Planctomyces
Holophaga NA

transform(.,Species= ifelse(Genus %in% Species, Species, NA))does not work.

Stefano Barbi
df |>
  mutate(species = case_when(mapply(grepl, sprintf("^%s", genus), species) ~ species,
                             is.na(genus) ~ species,
                             TRUE ~ NA_character_))

#> # A tibble: 3 × 2
#>   genus         species          
#>   <chr>         <chr>            
#> 1 Vulgatibacter Vulgatibacter sp.
#> 2 NA            Planctomyces     
#> 3 Holophaga     NA

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324282729&siteId=291194637