【发布时间】:2020-05-10 05:32:00
【问题描述】:
考虑以下玩具示例:
a <- c(rep(1,3))
b <- c(rep("b", 3))
names <- c("2019 Report", "XYZ Report", "2018 Report")
df <- as.data.frame(cbind(a, b, names))
我想修改names 列中的字符串,但仅限于包含年份的名称:
names_desired <- c("2019 Good Report", "XYZ Report", "2018 Good Report")
df_target <- as.data.frame(cbind(a, b, names, names_desired))
有很多方法可以通过过滤掉不包含年份的名称来做到这一点,例如(排序无关):
df %>%
filter(str_detect(names, "[:digit:]") == FALSE) %>%
mutate(names_desired = names) %>%
bind_rows(df %>%
filter(str_detect(names, "[:digit:]") == TRUE) %>%
mutate(names_desired = str_replace(names, "Report", "Good Report")))
我想要的是一种将名称与正则表达式匹配的方法,就像这样(不起作用):
df %>%
mutate(names_desired = str_replace(names, "[:digit:]{4} Report", "[:digit:]{4} Good Report"))
理想情况下,"[:digit:]{4}" 会返回匹配的数字,当然它不会。有没有办法做到这一点?
【问题讨论】: