r - 使用 R 中的多个分隔符从字符串中提取数字
问题描述
我有许多具有这种数据结构的输出文件:中位数(低,高),我想将所有数字分成它们自己的列,但由于括号和括号内的逗号分隔数字,我遇到了困难。
library(data.table)
# Data structure = median (low, high)
output <- c("9540000 (0,11140000)",
"8.81329 (0,8.81329)",
"27080000 (0,45290000)",
"23.4947 (0,63.2807)")
desired_out <- data.table(median = c(9540000, 8.81329, 27080000, 23.4947),
low = c(0, 0, 0, 0),
high = c(11140000, 8.81329, 45290000, 63.2807))
任何帮助将不胜感激...
解决方案
解决方案使用data.table
:
创建原始数据:
output <- c("9540000 (0,11140000)",
"8.81329 (0,8.81329)",
"27080000 (0,45290000)",
"23.4947 (0,63.2807)")
library(data.table)
df <- data.table(output)
使用 data.table 将字符串变量分为中位数、低位和高位tstrsplit
(我们使用 basegsub
去掉括号):
df[, c("median", "low", "high") := tstrsplit(gsub("[()]", "", output), "[ ,]")]
df 现在是:
output median low high 1: 9540000 (0,11140000) 9540000 0 11140000 2: 8.81329 (0,8.81329) 8.81329 0 8.81329 3: 27080000 (0,45290000) 27080000 0 45290000 4: 23.4947 (0,63.2807) 23.4947 0 63.2807
推荐阅读
- c# - 在linq中使用变量名查询表
- javascript - 设置样式位置时,Chrome Object 标签会多次加载:absolute
- php - 在不同的地方回显特定的行
- kubernetes - Kubernetes - 在 configmap 中指定 externalips
- android - 可以用相同的标签名称替换片段吗?
- javascript - 使用 jQuery 更改 html 内容后使用浏览器后退按钮
- ubuntu - 终端进程的可视化桌面
- google-analytics - 谷歌分析测量协议命中不正确?
- jquery - JS 中的 DIRECTORY_SEPARATOR 并且只更新一个页面标签
- php - Php Switch Case 未按预期工作