r语言 - 正则表达式忽略中间字符串



我有数据帧dat1。有没有办法使用 str_extract(( 和正则表达式从 colnames(dat1( 中仅提取"红白 40 R"?我计划稍后使用facet_wrap绘制它们,但在提取我想要的文本时遇到问题。对于我的实际代码,R# 将始终在字符串中,但是,留给 R# 的所有内容都可以变化。str_extract(( 之后的预期输出应为 txt。

dat1 <- data.frame(c(1,2,3,4), c(10, 20, 30, 40),
c(100, 200, 300, 400), c(1000, 2000, 3000, 4000))
colnames(dat1) <- c("red G white 40 R3", "red G white 40 R5", 
"red H white 40 R7", "red H white 40 R10")
txt <- c("red white 40 R", "red white 40 R", "red white 40 R", "red white 40 R")

这实际上取决于您的边缘情况。例如,您可以使用sub("(red ).* (white 40 R).*", "\1\2", colnames(dat1))但您也可以在这一点上编写colnames(dat1) <- rep("red white 40 R", ncol(dat1))

你想保留的词会改变吗?数字?也许你想要更强大的东西:

sub("(\w+).*?(\w+ \d+ \d).*", "\1\2", colnames(dat1))

如果我们不知道所需代码的完整用例,则很难提供帮助。

最新更新