【问题标题】:Create a new variable counting group between dates在日期之间创建一个新的变量计数组
【发布时间】:2021-04-26 15:11:38
【问题描述】:

我有一个包含键和日期列的数据集。

我想创建一个列,在 Date 列中的值之前的 30 天内按 Key 计算出现次数。

我遇到了麻烦,因为数据集中每一行的条件都会发生变化。

我该怎么做?

【问题讨论】:

标签: r date for-loop dplyr


【解决方案1】:

试试这个:


# first some data
library(lubridate)
library(data.table)

n <- 1e3

set.seed(100)
dat <- data.frame(
    Key = paste0( "Key-", sample( x=LETTERS[1:10], size=n, replace=TRUE ) ),
    Date = ymd("2018-01-01") + ceiling( runif( n=n, -400, +400 ) )
) %>% arrange( Date )
setDT(dat)

dat[, KeyCount := sum( Key == dat$Key & between( dat$Date, Date - 30, Date + 30 ) ), by=1:nrow(dat) ]

dat

first.data <- dat$Date[1]

dat[ Key == "Key-C" & Date < ymd("2016-11-28")+60, .(.SD, pluss30 = Date > ymd("2016-11-28")+30)  ]

dat 产生这个:


> dat
        Key       Date KeyCount
   1: Key-C 2016-11-28        6
   2: Key-A 2016-11-29        4
   3: Key-E 2016-11-30        5
   4: Key-D 2016-12-01        7
   5: Key-H 2016-12-02        6
  ---                          
 996: Key-A 2019-02-01        2
 997: Key-I 2019-02-03        4
 998: Key-D 2019-02-04        4
 999: Key-B 2019-02-05        5
1000: Key-J 2019-02-05        4

检查第一行是否有控制,我们看到:


> dat[ Key == first.key & Date < first.date+60, .(.SD, pluss30 = Date > first.date+30)  ]
   .SD.Key   .SD.Date .SD.KeyCount pluss30
1:   Key-C 2016-11-28            6   FALSE
2:   Key-C 2016-12-10            7   FALSE
3:   Key-C 2016-12-18            8   FALSE
4:   Key-C 2016-12-18            8   FALSE
5:   Key-C 2016-12-22            9   FALSE
6:   Key-C 2016-12-23            9   FALSE
7:   Key-C 2017-01-09           11    TRUE
8:   Key-C 2017-01-14           11    TRUE
9:   Key-C 2017-01-18           10    TRUE

第一个键计数似乎至少是正确的(在集合中的前 30 天内有 6 行,其编号为 6)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 2014-04-09
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 2013-01-05
    相关资源
    最近更新 更多