R 从文本中提取数据的最有效方法
我想知道从列中提取文本的最有效方法是否是在R 从文本中提取数据的最有效方法,r,text,data.table,R,Text,Data.table,我想知道从列中提取文本的最有效方法是否是在data.table中使用sub函数 例如,我们有以下数据集: 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")) 但是我想知道,这是最有效的方法吗?结合str\u extract和str\u remove可以减少时间 library(stringr) test1 <-
data.table
中使用sub
函数
例如,我们有以下数据集:
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"))
但是我想知道,这是最有效的方法吗?结合
str\u extract
和str\u remove
可以减少时间
library(stringr)
test1 <- test[rep(seq_len(.N), 1e6)]
test2 <- copy(test1)
system.time(test1[, Name := sub(".*? this is (.*?) and.*", "\\1", 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
库(stringr)
test1供参考,最好在询问性能/效率问题时提供一个可扩展的示例。在这种情况下,不同值的数量真的很重要,例如在@akrun的示例中,当使用by=
时,我们得到了接近0的计时system.time(test1[,Name:=sub(.*?这是(.*?)和.*”,“\\1”,a),by=a])
。例如:
library(stringr)
test1 <- test[rep(seq_len(.N), 1e6)]
test2 <- copy(test1)
system.time(test1[, Name := sub(".*? this is (.*?) and.*", "\\1", 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.*", "\\1", test1$a)
f2 <- function() str_remove(str_extract(test1$a, "this is \\w+"), "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