从文本中提取数据的最有效方法

我想知道从列中提取文本的最有效方法是使用data.table中的子函数.

例如,我们有以下数据集:

test <- data.table(a = c("Hello world,this is Tom and I am a guy","Hello world,this is Jack and I am a guy"))

我想提取名字.提取名称的一种方法是使用替换函数

test[,Name := sub(".*? this is (.*?) and.*","\\1",a)]

但我想知道,这是最有效的方式吗?

解决方法

结合str_extract和str_remove可以减少时间

library(stringr)
test1 <- test[rep(seq_len(.N),1e6)]
test2 <- copy(test1)
system.time(test1[,a)])    
#   user  system elapsed 
#  4.590   0.002   4.597 
system.time(test2[,Name :=  str_remove(str_extract(a,"this is \\w+"),"this is ")])
#   user  system elapsed 
#   2.259   0.076   2.339 

identical(test1$Name,test2$Name)
#[1] TRUE
library(microbenchmark)
f1 <- function()  sub(".*? this is (.*?) and.*",test1$a)
f2 <- function() str_remove(str_extract(test1$a,"this is ")

microbenchmark(f1(),f2(),unit = 'relative',times = 10L)  
#Unit: relative
#expr     min      lq     mean   median       uq      max neval
# f1() 2.12879 2.14592 2.145551 2.173798 2.188693 2.121836    10
# f2() 1.00000 1.00000 1.000000 1.000000 1.000000 1.000000    10

相关文章

HTML代码中要想改变字体颜色,常常需要使用CSS样式表。CSS是...
HTML代码如何让字体盖住图片呢?需要使用CSS的position属性及...
HTML代码字体设置 在HTML中,我们可以使用标签来设置网页中的...
在网页设计中,HTML代码的字体和字号选择是非常重要的一个环...
HTML(Hypertext Markup Language,超文本标记语言)是一种用...
外链是指在一个网页中添加一个指向其他网站的链接,用户可以...