【问题标题】:R - find occurrences of observation that happens in temporal proximity to another observationR - 查找发生在时间上接近另一个观察的观察事件
【发布时间】:2018-06-18 18:09:27
【问题描述】:

我有两个 dfs,一个是通话日期和客户 ID(日志),一个是失效日期和客户 ID(间隙)。对于任何客户的电话,我如何才能知道该客户在接下来的两天、两周和两年内是否有过失?

id = 唯一的客户 ID

call_date = 1 表示观察是调用

lapse_date = 1 表示观察是一个失误

logs <- structure(list(id = c(4968L, 4968L, 4968L, 4968L, 4968L, 4968L, 4968L, 4968L, 4968L, 4968L, 4968L, 4968L, 4968L, 4968L, 4968L, 4968L, 5818L, 5818L, 5818L, 5818L, 7118L, 7118L, 7118L, 7118L, 7118L, 7293L, 9451L, 9451L, 9793L, 9793L, 9793L, 9793L, 9793L, 9793L, 9793L), call_date = structure(c(16108, 16262, 16297, 16367, 16414, 16465, 16612, 16661, 16738, 16769, 16829, 16982, 17032, 17112, 17200, 17347, 16174, 16174, 16174, 16174, 16212, 16232, 17242, 17242, 17245, 16084, 16301, 16301, 16020, 16133, 16414, 16657, 16899, 17227, 17228), class = "Date")), class = "data.frame", row.names = c(NA, -35L), .Names = c("id", "call_date"))
gaps <- structure(list(id = c(4968L, 5818L, 5818L, 5818L, 5818L, 5818L, 5818L, 5818L, 5818L, 5818L, 5818L, 5818L, 5818L, 5818L, 5818L, 5818L, 5818L, 5818L, 5818L, 5818L, 5818L, 5818L, 7118L, 7118L, 7118L, 7118L, 7293L, 9451L, 9451L, 9793L, 9793L, 9793L), lapse_date = structure(c(14910, 15329, 15394, 15516, 15649, 15775, 15915, 15976, 16066, 16134, 16199, 16272, 16431, 16542, 16637, 16722, 16789, 16917, 17084, 17144, 17224, 17308, 15085, 15331, 16041, 16637, 15533, 14764, 16195, 15405, 15534, 15749), class = "Date")), class = "data.frame", row.names = c(NA, -32L), .Names = c("id", "lapse_date"))

我更喜欢在 tidyverse 工作,我可以命名我的第一个出生的 Hadley。

【问题讨论】:

    标签: r date time dplyr tidyverse


    【解决方案1】:

    以下是我可能解决此问题的方法。

    library(tidyverse)
    
    logs %>%
        inner_join(gaps) %>% 
        mutate(days_diff = as.numeric(lapse_date - call_date)) %>%
        mutate(two_days = as.numeric(days_diff %in% 0:2),
               two_weeks = as.numeric(days_diff %in% 0:14),
               two_years = as.numeric(days_diff %in% 0:730)) %>%
        select(-lapse_date, -days_diff) %>%
        group_by(id, call_date) %>%
        summarise_all(max)
    
          id call_date  two_days two_weeks two_years
       <int> <date>        <dbl>     <dbl>     <dbl>
     1  4968 2014-02-07        0         0         0
     2  4968 2014-07-11        0         0         0
     3  4968 2014-08-15        0         0         0
     4  4968 2014-10-24        0         0         0
    

    我们通过 id 加入,然后创建一个 days_diff 变量。之后我们创建了三个衡量日期差异的指标变量,最后我们通过 id 和 call_date 取这三个指标变量的最大值。

    【讨论】:

    • 老兄!谢谢!我确实必须为每个呼叫添加一个带有 ID 的数据集的“call_id”向量,以便我可以 group_by(id, call_id) 而不是 call_date 以不删除发生在同一日期的呼叫......但我已经我一直在我的桌子上敲了大约 10 个小时,试图弄清楚这一点。
    • 很高兴我能帮上忙。 call_id 添加听起来是个好主意
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    • 2018-11-28
    • 1970-01-01
    • 2015-10-27
    • 2016-11-05
    相关资源
    最近更新 更多