如何在R中提取后接+符号的数字并生成新列?
R语言提取后接+符号的数字解决方案
问题说明
现有如下样本数据:
sample_data <- data.frame( txtnumbers = c("text stuff +300.5","other stuff 40+ more stuff","text here -30 here too","30- text here","50+","stuff here 500+","400.5-" ), stringsAsFactors = F )
需要提取txtnumbers列中后接+符号的数字存入新列,不符合条件的返回NA,期望结果如下:
desired_data <- data.frame( txtnumbers = c("text stuff +300.5","other stuff 40+ more stuff","text here -30 here too","30- text here","50+","stuff here 500+","400.5-" ), desired_col = c(NA,40,NA,NA,50,500,NA), stringsAsFactors = F )
高效实现方案
使用stringr包的正则匹配功能即可精准完成需求,代码如下:
library(stringr) # 提取符合条件的数字并转为数值型 sample_data$desired_col <- as.numeric(str_extract(sample_data$txtnumbers, "\\d+(?:\\.\\d+)?(?=\\+)")) # 验证结果 print(sample_data)
正则表达式解析
\\d+:匹配1个或多个数字(?:\\.\\d+)?:可选的小数部分(非捕获组,仅用于匹配不额外提取)(?=\\+):正向预查,确保数字后面紧跟+符号,且+不会被包含在提取结果中
该方案能高效处理所有符合条件的场景,不符合规则的内容自动返回NA,完全匹配需求。
内容的提问来源于stack exchange,提问作者Neal Barsch
相关产品推荐
相关产品推荐

