【发布时间】:2019-09-26 09:57:46
【问题描述】:
假设我有以下数据:
library(tidyverse)
cf <- data.frame(x = c("a", "a", "a", "a", "b", "b", "b", "b", "c", "c", "c", "c", "d", "d", "e", "e"),
y = c("free", "with", "sus", "sus", "free", "with", "free", "sus", "sus", "with", "free", "sus", "free", "free", "with", "sus"))
> cf
x y
1 a free
2 a with
3 a sus
4 a sus
5 b free
6 b with
7 b free
8 b sus
9 c sus
10 c with
11 c free
12 c sus
13 d free
14 d free
15 e with
16 e sus
如果y 按组的最后一个值等于sus 并且sus 之前的最后一个值是with,我想获得一个等于1 的指标变量。在with 出现之前可以有多个sus,如组a。如果free 在with 之前最后出现,则它为零。
期望的输出:
x y sus_with
1 a free 0
2 a with 0
3 a sus 0
4 a sus 1
5 b free 0
6 b with 0
7 b free 0
8 b sus 0
9 c sus 0
10 c with 0
11 c free 0
12 c sus 0
13 d free 0
14 d free 0
15 e with 0
16 e sus 1
我在想这样的事情:
cf %>%
group_by(x) %>%
mutate(sus_with = if_else(row_number() == n() & y == "sus" & last(y == "with" & y != "free"), 1, 0))
参考:
How to find the date after the last occurrence of a certain observation in R?
How to find the last occurrence of a certain observation in grouped data in R?
有什么建议吗?
【问题讨论】: