Replace strings with numbers except those that contains 2020 or 2021 in R data frame

Viewed 64

I have a list of bigrams that I would like to filter. Want to remove all bigrams with numbers, except for those that contain 2021 or 2020

cat <- seq(1,7)
bg <- c("2021 test", "z1 trip", "00034 job","18 mar", "2021 day","business unit", "cycle work")
df <- data.frame(cat,bg)

I have tried nested grepl, but is does not work

df %>% filter(!grepl("[[:digit:]]",!grepl("2020|2021",bg)))

The expected output is: enter image description here

2 Answers

We could use a very simple regex pattern to check if there 4 digit number (\\b\\d{4}]]b) or (|) if there are no digits from start (^) to end ($) of the string

library(dplyr)
library(stringr)
df %>%
   filter(str_detect(bg, '\\b\\d{4}\\b|^[^0-9]+$')) %>%
   mutate(cat = row_number())

output

#  cat            bg
#1   1     2021 test
#2   2      2021 day
#3   3 business unit
#4   4    cycle work

If there are other digits such as '0004', and want only those starts with '20'

df %>%
   filter(str_detect(bg, '\\b20\\d{2}\\b|^[^0-9]+$')) %>%
   mutate(cat = row_number())

A simple way to do this could be:

subset(df, grepl("2021|2020", bg)|!grepl("\\d", bg))
#   cat            bg
# 1   1     2021 test
# 5   5      2021 day
# 6   6 business unit
# 7   7    cycle work
Related