我正在观察某个时间点是否在物料上发生了事件(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))
您可以在which.max
中使用summarise
并计算lastbefore
,我们可以为每个firstweek
从Material
中减去1。
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
类似地使用match
:
df %>%
group_by(Material) %>%
summarise(firstweek = Weeks[match(1, MG)],
lastbefore = Weeks[match(1, MG) - 1])