rstudio 中的 Gsub

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

我在 RStudio 中使用一个包含日期的列的数据框。有些行包含年份,例如 1687,其他行包含日期格式,例如 12/12/23,还有一些包含字符,例如“19e 世纪上半叶”、“1876-1879”、“19e-20e 之间”。我正在尝试从该列中提取数值和特殊字符 / 和 - 。

我从所有行中提取数值的方式期望包含“/”的行,因为我想保持原样。这是我的代码:

MR_all = data.frame(
  period = c("First half of 19e century", "1876-1879", "between 19e-20e", "12/12/23")
)

detect<- grepl("/|-", MR_all$period)

MR_all['period_3'] <- dplyr::case_when(detect == FALSE ~ gsub("[^0-9 / -]", "", MR_all$period))

这不起作用,因为“/”和“-”在输出中消失了。我非常感谢帮助更改代码,以便它提取数值和那些特殊字符。

rstudio gsub
© www.soinside.com 2019 - 2024. All rights reserved.