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

R语言使用正则表达式提取表格列字符串括号内多个数字咨询

解决方法

核心逻辑为用正则匹配()包裹的区间内容,再拆分出上下限数值,推荐使用tidyverse系列工具实现,代码简洁易读。

完整实现代码

# 加载依赖包
library(tidyverse)

# 构建示例数据
df <- structure(list(cutoff = c("2017-01-01", "2017-04-01", "2017-07-01"), 
               `KM Median rwToT (95% CI)` = c("2.1 (1.4 - 4.9)", "3.5 (2.1 - 4.7)", "3.7 (2.8 - 4.2)"), 
               `Restricted mean rwToT @ 24 months (95% CI)` = c("7.2 (3.9 - 10.2) [LogNorm]", 
                                                                "8.9 (6.6 - 10.8) [LogNorm]", "7.2 (6.2 - 8.4) [Weibull]")), 
               row.names = c(NA, -3L), class = c("tbl_df", "tbl", "data.frame"))

# 提取拆分数值
df_result <- df %>%
  # 同时处理两个目标列
  mutate(across(c(`KM Median rwToT (95% CI)`, `Restricted mean rwToT @ 24 months (95% CI)`), 
         list(
           # 提取括号外的点估计值
           est = ~as.numeric(str_extract(.x, "^\\d+\\.?\\d*")),
           # 提取95%CI下限
           ci_low = ~as.numeric(str_extract(.x, "(?<=\\()\\d+\\.?\\d*(?= -)")),
           # 提取95%CI上限
           ci_high = ~as.numeric(str_extract(.x, "(?<=- )\\d+\\.?\\d*(?=\\))"))
         ),
         # 自定义新列名格式
         .names = "{.col}_{.fn}"))

代码说明

  • 正则^\\d+\\.?\\d*匹配字符串开头的数值,即括号外的点估计值
  • 正则(?<=\\()\\d+\\.?\\d*(?= -)用零宽断言匹配(之后、-之前的CI下限数值
  • 正则(?<=- )\\d+\\.?\\d*(?=\\))用零宽断言匹配- 之后、)之前的CI上限数值
  • 若不需要保留原始列,可以在mutate之后加%>% select(-c(2,3))删除原始字符串列

基础R实现(无需安装额外包)

如果不想加载tidyverse,也可以用基础R的正则函数实现:

# 定义提取函数
extract_ci <- function(x) {
  ci_str <- regmatches(x, gregexpr("(?<=\\().*?(?=\\))", x, perl=TRUE))[[1]]
  ci_num <- as.numeric(strsplit(ci_str, " - ")[[1]])
  est <- as.numeric(sub(" .*", "", x))
  return(c(est=est, ci_low=ci_num[1], ci_high=ci_num[2]))
}

# 应用到目标列
km_res <- t(apply(df[,2,drop=FALSE], 1, extract_ci))
rm_res <- t(apply(df[,3,drop=FALSE], 1, extract_ci))
colnames(km_res) <- paste0("KM Median rwToT (95% CI)_", colnames(km_res))
colnames(rm_res) <- paste0("Restricted mean rwToT @ 24 months (95% CI)_", colnames(rm_res))
df_result <- cbind(df, km_res, rm_res)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 10:45:03