You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R语言的数据框中从字符型字符串提取整数?

解决字符列提取整数的问题

先修正你的gsub代码

你遇到的"\001"问题,是因为R中转义字符的规则:正则反向引用需要用双反斜杠\\1,单斜杠\1会被R解析成ASCII控制字符。修正后的代码:

gsub(".*?([0-9]+).*", "\\1", Not_Detect_134$Not_Detect_134)

更易用的替代方法

1. stringr包(推荐)

stringr的语法更直观,专门用于字符串处理:

# 安装并加载包
install.packages("stringr")
library(stringr)

# 提取第一个连续整数序列
str_extract(Not_Detect_134$Not_Detect_134, "\\d+")

# 若要提取所有整数(一个字符串含多个数字),用str_extract_all
unlist(str_extract_all(Not_Detect_134$Not_Detect_134, "\\d+"))

2. Base R原生方法(无需额外包)

用regmatches搭配regexpr/gregexpr实现:

# 提取第一个整数
regmatches(Not_Detect_134$Not_Detect_134, regexpr("\\d+", Not_Detect_134$Not_Detect_134))

# 提取所有整数
unlist(regmatches(Not_Detect_134$Not_Detect_134, gregexpr("\\d+", Not_Detect_134$Not_Detect_134)))

内容的提问来源于stack exchange,提问作者Tuan Jason

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 19:53:16