隨着data.table
的rleid()
功能可以通過用於分組:
library(data.table)
setDT(DF)[, .(PopDens = last(PopDens)), .(rleid(cluster), cluster)][, rleid := NULL][]
# cluster PopDens
#1: 1 7
#2: 2 9
#3: 1 12
#4: 3 14
#5: 1 16
有替代的方法來實現相同的結果:
DF[, .(PopDens = PopDens[.N]), .(rleid(cluster), cluster)][, rleid := NULL][]
DF[, .(PopDens = tail(PopDens, 1), .(rleid(cluster), cluster)][, rleid := NULL][]
DF[, .SD[.N], .(rleid(cluster), cluster)][, rleid := NULL][]
DF[, tail(.SD, 1), .(rleid(cluster), cluster)][, rleid := NULL][]
來源
2017-05-30 13:07:00
Uwe
巧妙使用'rle'! – Jaap
謝謝!完美的作品。 –