regex - R:在第一个分隔符出现时快速拆分字符串

标签 regex r string split

我有一个包含约 4000 万行的文件,我需要根据第一个逗号分隔符对其进行拆分。

以下使用stringr功能 str_split_fixed效果很好,但速度很慢。

library(data.table)
library(stringr)

df1 <- data.frame(id = 1:1000, letter1 = rep(letters[sample(1:25,1000, replace = T)], 40))
df1$combCol1 <- paste(df1$id, ',',df1$letter1, sep = '')
df1$combCol2 <- paste(df1$combCol1, ',', df1$combCol1, sep = '')

st1 <- str_split_fixed(df1$combCol2, ',', 2)

对更快的方法有什么建议吗?

最佳答案

更新
stri_split_fixed “stringi”的最新版本中的函数有 simplify可设置为 TRUE 的参数返回一个矩阵。因此,更新的解决方案将是:

stri_split_fixed(df1$combCol2, ",", 2, simplify = TRUE)

原始答案(带有更新的基准)

如果您对“stringr”语法感到满意并且不想偏离它太远,但您也想从速度提升中受益,请尝试使用“stringi”包:
library(stringr)
library(stringi)
system.time(temp1 <- str_split_fixed(df1$combCol2, ',', 2))
#    user  system elapsed 
#    3.25    0.00    3.25 
system.time(temp2a <- do.call(rbind, stri_split_fixed(df1$combCol2, ",", 2)))
#    user  system elapsed 
#    0.04    0.00    0.05 
system.time(temp2b <- stri_split_fixed(df1$combCol2, ",", 2, simplify = TRUE))
#    user  system elapsed 
#    0.01    0.00    0.01

大多数“stringr”函数都有“stringi”并行,但从这个例子可以看出,“stringi”输出需要一个额外的步骤来绑定(bind)数据以将输出创建为矩阵而不是列表。

以下是它与@RichardScriven 在评论中的建议的比较:
fun1a <- function() do.call(rbind, stri_split_fixed(df1$combCol2, ",", 2))
fun1b <- function() stri_split_fixed(df1$combCol2, ",", 2, simplify = TRUE)
fun2 <- function() {
  do.call(rbind, regmatches(df1$combCol2, regexpr(",", df1$combCol2), 
                            invert = TRUE))
} 

library(microbenchmark)
microbenchmark(fun1a(), fun1b(), fun2(), times = 10)
# Unit: milliseconds
#     expr       min        lq      mean    median        uq       max neval
#  fun1a()  42.72647  46.35848  59.56948  51.94796  69.29920  98.46330    10
#  fun1b()  17.55183  18.59337  20.09049  18.84907  22.09419  26.85343    10
#   fun2() 370.82055 404.23115 434.62582 439.54923 476.02889 480.97912    10

关于regex - R:在第一个分隔符出现时快速拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26263571/

相关文章:

javascript - 模式匹配永远不会终止

R:如何将我的数据格式化为多项式 Logit?

c++ - 从文件读取时使用 ">>"运算符后如何将光标移至下一行

regex - 在 RegEx 中将空格转换为制表符

删除行尾和新空格之间的数字

Java 正则表达式模式至少包含一个字母

r - 计算矩阵的特征值多少钱?

r - 创建基于多个变量的人口普查表

c# - 如何将文件中的整个文本连接到字符串中,避免字符串之间出现空行

python - 在某些字符串上匹配正则表达式的 URL 非常慢