I have this toy data as df
:
structure(list(Product_Name = c("Delicious Chips", "Creamy Tomato Soup",
"Cheesy Macaroni", "Savory Meatballs", "Crispy Chicken Tenders"
), Ingredients = c("Potato Slices | Vegetable Oil | Salt | Seasoning Blend",
"Tomatoes | Water | Cream | Onions | Salt | Spices", "Macaroni | Cheese Sauce | Milk | Butter | Salt | Pepper",
"Ground Meat | Breadcrumbs | Onions | Garlic | Spices", "Chicken Tenders | Breading Mix | Vegetable Oil | Salt | Pepper"
)), row.names = c(NA, 5L), class = "data.frame")
Here I want to find which rows contain "Salt"
in the Ingredients
variable.
Using library(tidyverse)
, initially I try df %>% str_detect(Ingredients, "Salt")
but I get Error: object 'Ingredients' not found
.
But when I change it to df %>% filter(str_detect(Ingredients, "Salt")
it returns a dataframe with the products matching the string.
I thought str_detect
needs a character vector or something coercible to one and I thought that Ingredients
fit that because when I do class(df$Ingredients)
it returns character. Why won't it take Ingredients
as an argument and what changes when it is wrapped into filter()
?
str_detect
, but the functionstr_detect
goes insidemutate
/filter
or a similar function - not on it's own. E.g.df %>% mutate(salt_flag = str_detect(Ingredients, "Salt"))
fruit <- c("apple", "banana", "pear", "pineapple") str_detect(fruit, "a")
which is from the str_detect documentation -- and if it should always go into a mutate() or similar, how do I learn that or find it out?!mutate
has a...
argument which allows all the columns ofdf
to be passed through as separate objects, which then can be picked up bystr_detect
when it is nested insidemutate
.str_detect
only has arguments forstring=
andpattern=
and no...
, so needs a string directly passed in. So you could do something likedf %>% pull(Ingredients) %>% str_detect(pattern="Salt")
to sort it out as well.%>%
you could also dostr_detect(df$Ingredients, "Salt")
by selecting the column explicitly from thedf
object in the global environment/workspace. And you could assign that back using base R logic then too -df$salt_flag <- str_detect(df$Ingredients, "Salt")