【问题标题】:First time for an event and last time before第一次参加活动,最后一次参加
【发布时间】:2020-09-05 08:45:54
【问题描述】:

我正在观察某个时间点是否在材料上发生了事件 (MG)。每次观察之间的持续时间从 1 到 3 周或更多周不等。现在我想找出事件发生的第一周和前一周。

df <- data.frame(Weeks=c(1,2,3,5,1,2,7,10), Material=c(rep("A",4),rep("B",4)), MG=c(0,0,0,1,0,0,1,1))

这就是我想要的结果

outputwanted <- data.frame(Material=c("A","B"), firstweek=c(5,7), lastbefore=c(3,2))

我已经尝试“切片”来查找它第一次发生的时间,但我可以将它也用于我的其他目的吗?

df %>% group_by(Material) %>% slice(which.max(MG))

【问题讨论】:

    标签: r dplyr slice


    【解决方案1】:

    您可以在summarise 中使用which.max 并计算lastbefore,我们可以为每个Materialfirstweek 中减去1。这是假设每组中总是至少有 1 个,即Material

    library(dplyr)
    df %>%
      group_by(Material) %>%
      summarise(firstweek = Weeks[which.max(MG)], 
                lastbefore = Weeks[which.max(MG) - 1])
    
    
    #  Material firstweek lastbefore
    #  <chr>        <dbl>      <dbl>
    #1 A                5          3
    #2 B                7          2
    

    如果有没有 1 的组,我们可以使用 match

    df %>%
      group_by(Material) %>%
      summarise(firstweek = Weeks[match(1, MG)], 
                lastbefore = Weeks[match(1, MG) - 1])
    

    which

    df %>%
      group_by(Material) %>%
      summarise(firstweek = Weeks[which(MG == 1)[1]], 
                lastbefore = Weeks[which(MG ==1)[1] - 1])
    

    【讨论】:

    • 这个解决方案很有帮助,谢谢!但是,观察时间之间的间隔并不相等;有时是一周,有时是两到三周的观察间隔。那么这个解决方案不起作用。当然,我应该在问题中提供这些信息..
    • @user4631839 对不起,你的意思是你想让 t0 得到第一个 MG 对应的 Week 值吗?喜欢df %&gt;% group_by(Material) %&gt;% summarise(firstweek = Weeks[which.max(MG)], lastbefore = firstweek - 1)
    • 更新了答案。希望它能回答你的问题。
    • @user4631839 当没有事件发生时你想要什么输出?如果您使用match 选项,它会返回NA
    • 添加了另一个使用which的选项,它也返回NA
    【解决方案2】:

    有了data.table,我们可以做到

    library(data.table)
    setDT(df)[, {i1 <- which.max(MG)
               .(firstweek = Week[i1],
                  lastbefore = Week[i1-1])} , Material]
    

    【讨论】:

      猜你喜欢
      • 2021-07-07
      • 1970-01-01
      • 1970-01-01
      • 2013-09-18
      • 1970-01-01
      • 1970-01-01
      • 2013-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多