Lösung 3:
Zuerst bauen die logische grep
expression
alle Spalten angehängt wird. Dann eval
der Gesamtausdruck in einem Rutsch:
dt <- data.table(a=c("a1","bb","1c"),b=c("A1","BB","1C"))
search.data.table <- function(x, pattern) {
nms <- names(x)
string <- eval(expression(paste0("grepl('",
pattern,
"', ",
nms,",
ignore.case=TRUE, perl=FALSE)",
collapse = " | ")))
x[eval(as.call(parse(text=string))[[1]])]
}
search.data.table(dt, "a1")
# a b c
# 1: Aa1 A1 a
# 2: bb a1 b
Benchmarking
# functions
Raffael <- function(x, pattern) {
# unfortunately this implementation throws an error so I can't run the benchmark test.
# Any help?
combined <- apply(x,1,function(r) paste(r,collapse="/%/"))
grepped <- grepl(pattern,apply(x,1,function(r) paste(r,collapse="/")))
x[grepped,]
}
Arun <- function(x, pattern) {
ldt <- x[, lapply(.SD, function(x) grepl(pattern, x, perl=TRUE, ignore.case=TRUE))]
x[rowSums(ldt)>0]
}
DanielKrizian <- function(x, pattern) {
nms <- names(x)
string <- eval(expression(paste0("grepl('", pattern, "', ",nms,", ignore.case=TRUE, perl=FALSE)",collapse = " | ")))
x[eval(as.call(parse(text=string))[[1]])]
}
# generate 1000 x 1000 benchmark data.table
require(data.table)
expr <- quote(paste0(sample(c(LETTERS,tolower(LETTERS),0:9),12, replace=T)
,collapse=""))
set.seed(1)
BIGISH <- data.table(matrix(replicate(1000*1000,eval(expr)),nrow = 1000))
object.size(BIGISH) # 68520912 bytes
# test
benchmark(
DK <- DanielKrizian(BIGISH,"qx"),
A <- Arun(BIGISH,"qx"),
replications=100)
Ergebnisse
test replications elapsed relative user.self sys.self user.child sys.child
2 A <- Arun(BIGISH, "qx") 100 57.72 1.000 51.95 0.44 NA NA
1 DK <- DanielKrizian(BIGISH, "qx") 100 59.28 1.027 53.72 0.50 NA NA
identical(DK,A)
[1] TRUE
+1 versuchen Sie, die Datentabellen zu replizieren setzen? (Ich meine das jQuery-Plugin) – Michele
@Michele nicht vertraut mit 'datatables', aber [Beispiel hier] (https://datatables.net/) hat" Suche "Texteingabefeld, das ziemlich genau das Gleiche tut über –
... der Link, den Sie setzen, ist genau "Datatables" – Michele