Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count Unique Word Matches in Column

Tags:

r

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
like image 381
RStudent Avatar asked Jul 10 '26 11:07

RStudent


1 Answers

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)

like image 166
DaveArmstrong Avatar answered Jul 12 '26 02:07

DaveArmstrong