How do I write code to find the rows with the word "Alternative" under style. BUT not just "Alternative" on its own but "Alternative" combined with other words. Here the dataframe is called metals
style
id brand_id brand_name origin formed split fans style
5 1038 Keldian Norway 2005 2005 54 Adult
6 2022 Dawn Of Ashes USA 2001 2001 17 Aggrotech
7 43 Sepultura Brazil 1984 2003 1185 Alternative
8 3388 Louna Russia 2007 2008 5 Alternative rock
9 785 Stam1na Finland 1992 1996 78 Alternative thrash
Its easy to find the columns under style with "Alternative" only like here:
metals[metals$style == "Alternative",]
but I want to find the rows with "Alternative" under style, regardless if it has another word besides it like rock of thrash or not, which means I want 3 rows printed with the sample I posted above
CodePudding user response:
Try this. It's also a good way to share a minimal reproducible example which enables us to be able to run and improve code.
library(tidyverse)
tribble(~id, ~style,
5, "Adult",
6, "Aggrotech",
7, "Alternative",
8, "Alternative rock",
9, "Alternative thrash"
) |>
filter(str_detect(style, "Alternative"))
#> # A tibble: 3 × 2
#> id style
#> <dbl> <chr>
#> 1 7 Alternative
#> 2 8 Alternative rock
#> 3 9 Alternative thrash
Created on 2022-05-11 by the reprex package (v2.0.1)
CodePudding user response:
Use grepl
to match a pattern:
metals[grepl("(?i)Alternative", metals$style),]
Note that the (?i)
flag is used to make the match case-insensitive so that you would find values such as "alternative" or even " "alterNAtive" too. If that's not wanted or necessary just leave it out.