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

在R语言中使用stringr包提取方括号内数值的问题

使用stringr提取方括号内数值的解决方案

方法一:用str_extract精准匹配方括号内内容

先加载stringr包,通过正则断言定位方括号之间的数值字符串,再转为数值型:

# 加载stringr包
library(stringr)

# 构造示例数据(替换为你的实际数据框即可)
df <- data.frame(
  participant = c("s07", "s08", "s10", "s11"),
  position_1 = c("[-3.96002452]", "[-2.43317811]", "[0.57034622]", "[-2.93552563]"),
  position_2 = c("[-6.40075519]", "[-2.26514695]", "[-0.98081968]", "[-2.91766826]"),
  stringsAsFactors = FALSE
)

# 提取方括号内内容并转换为数值
df$position_1 <- as.numeric(str_extract(df$position_1, "(?<=\\[).*?(?=\\])"))
df$position_2 <- as.numeric(str_extract(df$position_2, "(?<=\\[).*?(?=\\])"))

# 查看处理后的数据结构
str(df)

方法二:用str_remove_all直接去除方括号

更简洁的方式是删除所有方括号,剩余内容直接转数值型:

# 去除方括号并转换类型
df$position_1 <- as.numeric(str_remove_all(df$position_1, "\\[|\\]"))
df$position_2 <- as.numeric(str_remove_all(df$position_2, "\\[|\\]"))

结果验证

处理后的数据框结构如下,与预期一致:

'data.frame':	4 obs. of  3 variables:
 $ participant: chr  "s07" "s08" "s10" "s11"
 $ position_1 : num  -3.96 -2.43 0.57 -2.94
 $ position_2 : num  -6.4 -2.27 -0.981 -2.918

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 12:40:37