0

I have a df consisting of two columns:

df <- data.frame(Date = c("01-01-2016","02-01-2022","05-01-2022", "21-12-2022","03-09-2021", "21-12-2017"),
                 Value = c(14.2, 23.2, "bc", "bc", 78.2, "bc" ))

I want to count the sum of occurences of the word "bc" in the grouped by date, so tried the following:

df2 <- df %>% group_by(Date) %>% summarise(length(grep("bc", Value)))

but this gives me the total number of occurence of "bc" in the entire df which is 3

WHat I want is

**Expected output **

Date bc_total
2022 2
2017 1
Bubbles
  • 5
  • 4

1 Answers1

0

Code

library(dplyr)
library(lubridate)

df <- data.frame(Date = c("01-01-2016","02-01-2022","05-01-2022", "21-12-2022","03-09-2021", "21-12-2017"),
                 Value = c(14.2, 23.2, "bc", "bc", 78.2, "bc" ))
df %>% 
  mutate(Year = year(dmy(Date))) %>% 
  group_by(Year,Value) %>%
  summarise(Count=n()) %>% 
  as.data.frame()

Output

 Year Value Count
1 2016  14.2     1
2 2017    bc     1
3 2021  78.2     1
4 2022  23.2     1
5 2022    bc     2

hope this helps :)