可以試試看tapply做 會比迴圈再快一點
我自己模擬了一筆13000左右的資料只比迴圈快1.86倍
我有試過把比過的跳掉,可是發現變更慢
還在想有沒有什麼方法更快
code:
data$Session = unlist(tapply(data$Time, data$ID, function(v){
output = rep(0, length(v))
i = 1
session_num = 1
repeat
{
loc = as.numeric(v - v[i], unit='hours') < 1 & output == 0
output[loc] = session_num
session_num = session_num + 1
i = i + sum(loc)
if(i > length(v))
break
}
output
}))
模擬資料:
set.seed(100)
n = 2100
data = data.frame(ID = rep(1:n, ceiling(runif(n) * 10) + 1))
nrow(data)
# 13812
data$Time = Reduce(c, tapply(rep(1, nrow(data)), data$ID, function(v){
start_time = strptime("2014-08-01 00:00:00", "%Y-%m-%d %H:%M:%S")
as.POSIXlt(sort(start_time + round(86400 * runif(length(v)))))
}))
迴圈:5.301304 secs
tapply: 2.846163 secs