【问题标题】:Create incremental value with restart with condition within ID使用 ID 内的条件重新创建增量值
【发布时间】:2019-12-01 13:10:26
【问题描述】:

所以我有 2 个字段的数据,ID 和时间戳

ID Time
1 12
1 15
1 16
2 12
2 11

如果时间和前一次之间的差异小于 2,例如在同一 ID 内,我想增加,除非保持相同的值并在 ID 不同时从 1 重新开始。

期望的输出:

ID Time ID_SESSION
1 12 1
1 15 1
1 16 2
2 12 1
2 11 1

在 dplyr/sparklyr 中需要使用 R/ 实现 spark

【问题讨论】:

  • 那么你的问题是什么?

标签: r apache-spark dplyr sparklyr


【解决方案1】:

使用基础 R 的单线,

with(df, ave(Time, ID, FUN = function(i)cumsum(c(TRUE, diff(i) <= 2))))
#[1] 1 1 2 1 2

【讨论】:

    【解决方案2】:

    也许我们需要

    library(dplyr)
    df1 %>%
       group_by(ID) %>% 
       mutate(ID_SESSION = (lag(c(FALSE, diff(Time) > 2), default= FALSE)) + 1)
    

    或与data.table 在单行中

    library(data.table)
    setDT(df1)[, ID_SESSION := shift(c(FALSE, diff(Time) > 2), fill = FALSE) + 1, ID]
    df1
    #   ID Time ID_SESSION
    #1:  1   12          1
    #2:  1   15          1
    #3:  1   16          2
    #4:  2   12          1
    #5:  2   11          1
    

    数据

    df1 <- structure(list(ID = c(1L, 1L, 1L, 2L, 2L), Time = c(12L, 15L, 
    16L, 12L, 11L)), class = "data.frame", row.names = c(NA, -5L))
    

    【讨论】:

    • 您好,我尝试了您的 dplyr 解决方案,但出现以下错误:错误:org.apache.spark.sql.AnalysisException: Window function lag(named_struct(col1, FALSE, col2, diff(TIMESTAMP ) > 1800.0), 1, false) 需要订购窗口,请添加 ORDER BY 子句。例如 SELECT lag(named_struct(col1, FALSE, col2, diff(TIMESTAMP) > 1800.0), 1, false)(value_expr) OVER (PARTITION BY window_partition ORDER BY window_ordering) from table;
    • Time = TIMESTAMP 从我的例子来看,基本上是一样的
    • @josef_joestarr 你在我的例子中使用相同的示例数据吗,因为我没有收到错误
    • tbl(sc,'main_view_ui') %>% group_by(GA_ID) %>% 排列(GA_ID, TIMESTAMP) %>% mutate(ID_SESSION = (lag(c(FALSE, diff(TIMESTAMP) > 1800), 默认= FALSE)) + 1)
    • 是的,它只是一个浮点数,ID 是文本
    猜你喜欢
    • 2021-05-21
    • 1970-01-01
    • 2013-02-25
    • 2014-05-24
    • 2011-04-21
    • 1970-01-01
    • 2022-09-29
    • 2012-12-23
    • 1970-01-01
    相关资源
    最近更新 更多