Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R frequency count by matching strings

Tags:

r

Please can someone help me with this question? Thanks a lot!

I have some data like this:

    A             B
fruit     red apple
fruit   green apple
fruit  yellow apple
fruit          kiwi
fruit   golden kiwi
juice   apple juice
juice  orange juice

and I want to get the following:

    A             B         freq
fruit         apple            3
fruit          kiwi            2
juice         apple            1
juice        orange            1

I can provide a vector of strings to search for in B (i.e. I know I want to look for "apple", "kiwi", and "orange"). If for example there is a "banana" in "fruit" and I don't have "banana" in the list of items I want to search for, simply display "banana" in the result with freq 1.

like image 828
scat5218 Avatar asked Aug 01 '26 13:08

scat5218


1 Answers

Counting the number of observations with a particular value is a one-liner with table:

library(stringr)
table(paste(df$A, str_extract(df$B, paste(lookingfor, collapse="|")), sep="."))
#  fruit.apple   fruit.kiwi  juice.apple juice.orange 
#            3            2            1            1 

Here, paste(lookingfor, collapse="|") generates a regex looking for all your words, str_extract extracts the words you're looking for, the outer paste groups together the A variable with the extracted value (separating with a .) and table computes the counts for each pairing.

like image 121
josliber Avatar answered Aug 04 '26 06:08

josliber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!