我在 R 中使用一个包含日期的列的数据框。有些行包含年份,例如 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))
这不起作用,因为“/”和“-”在输出中消失了。我非常感谢帮助更改代码,以便它提取数值和那些特殊字符。
您的问题不在于
gsub
,而在于case_when
的使用。如果 detect
是 TRUE
,您应该指定会发生什么。假设正则表达式正在按照您的想法进行操作,您应该按如下方式重写代码:
library(dplyr)
MR_all <- data.frame(
period = c("First half of 19e century", "1876-1879", "between 19e-20e", "12/12/23")
)
MR_all %>%
mutate(period_3 = case_when(!grepl("/|-", period) ~ gsub("[^[:digit:]]", "", period),
TRUE ~ period))
# # A tibble: 4 × 2
# period period_3
# <chr> <chr>
# 1 First half of 19e century 19 # no `/` or `-` -> remove non digits
# 2 1876-1879 1876-1879 # `-` detected -> keep as is
# 3 between 19e-20e between 19e-20e # `-` detected -> keep as is
# 4 12/12/23 12/12/23 # `/` detected -> keep as is