replace two prefix with nothing in R

43 Views Asked by At

I would like to remove columns with the prefix 2023 or 2022.

vec = c("2022-10-16", "2022-10-23", "2022-10-30", "2022-11-06", "2023-01-01", "2023-01-15")

I know this is incorrect but is there something similar?

gsub("2023" | "2022", "", vec)
1

There are 1 best solutions below

0
Mark On
df <- data.frame(
    vec = c("2022-10-16", "2022-10-23", "2022-10-30", "2022-11-06", "2023-01-01", "2023-01-15"),
    value = 1:6)


# if you meant actually meant remove the rows that start with 2023 or 2022, then you can use this:

df[!grepl("^(202[23])", df$vec),]
# or using dplyr:
df %>% dplyr::filter(!grepl("^(202[23])", vec))

# if you wanted to just remove the year from the date, then you can use this:
df$vec <- gsub("^202[23]", "", df$vec)

# or with tidyverse
library(tidyverse)
df |> mutate(vec = str_remove(vec, "^202[23]"))