在我的一個應用程序中,有一段代碼根據另一個對象中的值檢索data.table
對象的信息。將一個範圍的端點與一個序列合併
# say this table contains customers details
dt <- data.table(id=LETTERS[1:4],
start=seq(as.Date("2010-01-01"), as.Date("2010-04-01"), "month"),
end=seq(as.Date("2010-01-01"), as.Date("2010-04-01"), "month") + c(6,8,10,5),
key="id")
# this one has some historical details
dt1 <- data.table(id=rep(LETTERS[1:4], each=120),
date=seq(as.Date("2010-01-01"), as.Date("2010-04-30"), "day"),
var=rnorm(120),
key="id,date")
# and here I finally retrieve my historical information based one customer detail
#
library(data.table)
myfunc <- function(x) {
# some code
period <- seq(x$start, x$end, "day")
dt1[.(x$id, period)][, mean(var)]
# some code
}
以獲取所有的結果我用adply
library(plyr)
library(microbenchmark)
> adply(dt, 1, myfunc)
id start end V1
1: A 2010-01-01 2010-01-07 0.3143536
2: B 2010-02-01 2010-02-09 -0.5796084
3: C 2010-03-01 2010-03-11 0.1171404
4: D 2010-04-01 2010-04-06 0.2384237
> microbenchmark(adply(dt, 1, myfunc))
Unit: milliseconds
expr min lq median uq max neval
adply(dt, 1, myfunc) 8.812486 8.998338 9.105776 9.223637 88.14057 100
你知道的方式,以避免adply
呼叫並執行上述一個data.table
聲明?或者無論如何一個更快的方法? (標題編輯建議更受歡迎,我想不出一個更好的,謝謝)
如果除了序列之外還返回第一個'[]'中的'end',那麼您可以更清楚一點,那麼您不需要進行最後的合併。另一種選擇是從'by'計算'end'。無論哪種情況,您都可以在開始之前通過取消設置'dt'的密鑰來清除表達式中的'as.list'或'setkey'。 – eddi
@eddi和序列一起返回'end'應該與你的第一個'[]'相同'nomatch = 0'innit?無論如何,謝謝你們,你們**非常有幫助! – Michele
@Michele,我不確定你說的是哪一步,但是在某些時候他們確實收斂:) – eddi