I am interested in counting the unique number of matches in a column to a list of words. I want to count to be in a new column in the dataframe, so that each row has a count.
For example:
person_id <- c("001", "002", "003")
grocery_list <- c("apple orange orange kiwi", "eggs milk apple apple", "apple orange banana")
df <- data.frame(person_id, grocery_list)
fruit_list <- c("apple", "orange", "banana")
The output would be:
person_id grocery_list fruit_count
001 apple orange orange kiwi 2
002 eggs milk apple apple 1
003 apple orange banana 3
This should do it:
library(tidyverse)
person_id <- c("001", "002", "003")
grocery_list <- c("apple orange orange kiwi", "eggs milk apple apple", "apple orange banana")
df <- data.frame(person_id, grocery_list)
fruit_list <- c("apple", "orange", "banana")
df %>%
rowwise() %>%
mutate(fruit_count = sum(str_detect(grocery_list, fruit_list)))
#> # A tibble: 3 × 3
#> # Rowwise:
#> person_id grocery_list fruit_count
#> <chr> <chr> <int>
#> 1 001 apple orange orange kiwi 2
#> 2 002 eggs milk apple apple 1
#> 3 003 apple orange banana 3
Created on 2022-06-03 by the reprex package (v2.0.1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With