首页 > 解决方案 > 在单词和数字之间替换逗号+空格

问题描述

我有:

x<- c("20% cotton 30% textile 50% other", "75.5% plastic 24.5% other")

我怎样才能将其更改为

c("20% cotton, 30% textile, 50% other", "75.5% plastic, 24.5% other")

?

gsub("[[:alpha:]] ", ", ", y) 不起作用,因为“吃”是单词中的最后一个符号。

标签: r

解决方案


基于模式的一个选项是匹配一个或多个空格 ( +) 后跟\\d作为组 ( ) 捕获的数字 ( (...)),并在 中replacement插入,后跟一个空格和\\1捕获组的反向引用 ( )

gsub(" +(\\d)", ", \\1", x)
#[1] "20% cotton, 30% textile, 50% other" "75.5% plastic, 24.5% other" 

推荐阅读