![](/img/trans.png)
[英]How to divide all previous observations by the last observation iteratively within a data frame column by group in R and then store the result
[英]Last observation of the previous group
我想知道,如果我有可以按變量分組的數據,我怎樣才能獲得上一組的最后觀察值?
我有以下數據:
dt <- data.table(a=c(1,1,1,2,2,2,2,2,3,3,3,3,3,3,4,4,5,5,5,5,5), b=sample.int(21))
我想創建一個新的 data.table,它具有組 ID 以及該組的最后一次觀察與上一組的最后一次觀察之間的差異。 所以從上面我會得到:
a c
1: 1 NA
2: 2 9
3: 3 1
4: 4 -8
5: 5 5
謝謝!
我們按 'a' 分組,得到 'b' 的last
元素,然后通過shift
ing 取 'c' 的lag
dt[, .(c = last(b)), a][, c:= shift(c)][]
這是一種方法:
dt[, c := b * (1:.N == .N), by = a] ## get last row within the group
dt <- dt[b == c] ## filter data.table to get rows of interest
dt[, c := shift(c, type = "lag") - c][] ## getting difference using shift with lag argument
# a b c
#1: 1 11 NA
#2: 2 10 NA
#3: 3 18 9
#4: 4 19 -7
#5: 5 12 -8
set.seed(1)
dt <- data.table(a=c(1,1,1,2,2,2,2,2,3,3,3,3,3,3,4,4,5,5,5,5,5), b=sample.int(21))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.