顯然,從版本1.10.2開始有一個新的實現方法。
library(data.table)
cols <- grep("bar|baz", names(mydt), value = TRUE)
mydt[, ..cols]
看來工作最快走出發佈的解決方案。
# Creating a large data.table with 100k rows, 32 columns
n <- 100000
foo_cols <- paste0("foo", 1:30)
big_dt <- data.table(bar = rnorm(n), baz = rnorm(n))
big_dt[, (foo_cols) := rnorm(n)]
# Methods
subsetting <- function(dt) {
subset(dt, select = grep("bar|baz", names(dt)))
}
usingSD <- function(dt) {
dt[, .SD, .SDcols = names(dt) %like% "bar|baz"]
}
usingWith <- function(dt) {
cols <- grep("bar|baz", names(dt), value = TRUE)
dt[, cols, with = FALSE]
}
usingDotDot <- function(dt) {
cols <- grep("bar|baz", names(dt), value = TRUE)
dt[, ..cols]
}
# Benchmark
microbenchmark(
subsetting(big_dt), usingSD(big_dt), usingWith(big_dt), usingDotDot(big_dt),
times = 5000
)
#Unit: microseconds
# expr min lq mean median uq max neval
# subsetting(big_dt) 462.2 596.2 1383 680.0 1176.8 62292 5000
# usingSD(big_dt) 459.8 583.7 1279 669.5 1172.7 57934 5000
# usingWith(big_dt) 386.6 493.6 1209 572.6 1039.0 61313 5000
# usingDotDot(big_dt) 364.1 464.6 1063 538.1 945.5 67741 5000
你可以做'mydt [,grep的(C( 「欄|巴茲」),名(mydt)),與= FALSE]'但是我想'with'創建一個副本。 –
可能會有所幫助:http://stackoverflow.com/q/13383840和http://stackoverflow.com/q/12603890 – shadowtalker
@DavidArenburg不要以爲它會創建一個副本。 – nicola