Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to count specific occurrences of strings within chr data into a new column

I have a dt similar to below, with chr data held in the Description column like below. I need to count the number of times certain strings of characters occur in that column, and sum them in the Occurrences column.

In the table below, it would be counting the number of times "A18" or "A19" appears.

ID Date Description Occurrences
1 2020-01-01 A1901,A1804,A2008,AB06 2
2 2020-01-14 A1402,A1805,A1902 2
3 2018-02-25 A1702 0

I’m very new to R and datatables, so haven’t tried much. I’ve searched, but only found how to count occurrences of whole strings, not within them.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use str_count:

library(stringr)
library(dplyr)
df %>% 
  mutate(Occurences2 = str_count(Description, "A18|A19"))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading