簡體   English   中英

計數值比當前值大 1 的先前出現次數

[英]Count prior occurences of value one greater than current value

我正在嘗試創建一個列,其中包含比當前值大 1 的值的先前出現次數(按日期排序)。 在此處提供的示例中,我在標記為“想要”的列中手動創建了我想要的值,該值等於 RoundNo 的先前出現次數(按“日期”排序)的次數,這些次數比焦點行大 1回合數我需要為每個單獨的 InvestorID 按組單獨計算。

因此,第一行“想要的”值等於投資者 1 的先前 RoundNo 的計數,其中 RoundNo == 3(也就是比第一行的 RoundNo 大 2)。 所以在這種情況下,這將是 0。類似地,對於第二行,“想要的”值是投資者 1 的先前 RoundNo 的計數,其中 RoundNo == 2(也就是比第二行的 RoundNo 大 1)。 所以在這種情況下,這將是 1。希望得到任何幫助。 代碼示例如下。 謝謝!

dt = as.data.table(cbind(c(rep(1,7),rep(2,7)),
                         c("2019-08-01","2019-09-01","2019-10-01","2019-11-01","2019-12-01","2021-04-01","2021-10-01",
                           "2019-01-01","2019-02-01","2019-04-01","2019-08-01","2019-09-01","2019-10-01","2019-11-01"),
                         c(2,1,2,2,1,3,2,1,2,3,2,1,3,1)))
names(dt) = c("InvestorID","date","RoundNo")
wanted = c(0,1,0,0,3,0,1,0,0,0,1,2,0,2)
dt$wanted = wanted

1)定義一個函數Count ,它計算其向量輸入的每個元素等於 1 加上其最后一個元素的次數。 然后使用 rollapplyr 將其應用於每個 InvestorID 內的序列號。

library(zoo)

Count <- function(x) sum(x == tail(x, 1) + 1)
dt[, wanted := rollapplyr(as.numeric(RoundNo), 1:.N, Count), by = InvestorID]

2)另一種方法是使用自左連接在其中的第一個實例dt別名為a是左接合的第二實例dt別名為b相關聯的那些b行,其來自相同InvestorID之前或在與來a排。 由集團a排,走在適當的總和b行。

library(sqldf)

sqldf("select a.*, sum(a.RoundNo + 1 == b.RoundNo) wanted
  from dt a
  left join dt b on a.InvestorID = b.InvestorID and b.rowid <= a.rowid
  group by a.rowid")

3)此替代方案僅使用 data.table。 Count來自(1)。

dt[, wanted := sapply(1:.N, function(i) Count(as.numeric(RoundNo)[1:i])), 
     by = InvestorID]

另一個使用Reduce data.table解決方案:

dt[order(date),.(date,
                 result=lapply(Reduce('c',as.numeric(RoundNo),accumulate=T),
                                    function(x) sum(x==last(x)+1)),
                 wanted), by=InvestorID]

    InvestorID       date result wanted
 1:          2 2019-01-01      0      0
 2:          2 2019-02-01      0      0
 3:          2 2019-04-01      0      0
 4:          2 2019-08-01      1      1
 5:          2 2019-09-01      2      2
 6:          2 2019-10-01      0      0
 7:          2 2019-11-01      2      2
 8:          1 2019-08-01      0      0
 9:          1 2019-09-01      1      1
10:          1 2019-10-01      0      0
11:          1 2019-11-01      0      0
12:          1 2019-12-01      3      3
13:          1 2021-04-01      0      0
14:          1 2021-10-01      1      1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM