将 R 中的两个前缀替换为空

问题描述 投票:0回答:1

我想删除前缀为 2023 或 2022 的列。

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

我知道这是不正确的,但是有类似的东西吗?

gsub("2023" | "2022", "", vec)
r string text-mining gsub
1个回答
0
投票
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]"))
© www.soinside.com 2019 - 2024. All rights reserved.