【问题标题】:Count prior occurences of value one greater than current value计算比当前值大一的值的先前出现次数
【发布时间】:2024-01-03 06:55:01
【问题描述】:

我正在尝试创建一个列,其中包含比当前值大一的值的先前出现次数(按日期排序)。在此处提供的示例中,我在标记为“wanted”的列中手动创建了我想要的值,该值等于 RoundNo 的先前出现次数(按“日期”排序)等于焦点行大一的计数圆号我需要为每个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

【问题讨论】:

    标签: r count data.table sequence


    【解决方案1】:

    1) 定义一个函数Count,它计算其向量输入的每个元素等于1 加上其最后一个元素的次数。然后使用 rollapplyr 将其应用于RoundNo 的连续更大的前导序列。

    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 别名为@ 的第二个实例987654327@ 关联来自同一 InvestorID 并位于 a 行之前或处的那些 b 行。按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]
    

    【讨论】:

      【解决方案2】:

      另一个使用Reducedata.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
      

      【讨论】:

        最近更新 更多