以下是数据:
df0 <-
data.frame(id = 1:13,
type = c("not_applicable",
"new",
"same",
"same",
"not_applicable",
"new",
"new",
"new",
"same",
"same",
"not_applicable",
"new",
"same"))
我想将索引分配给以"new"开头的运行,并将零分配给"NOT_APPLICATIONAL"值,使用dplyr
.每个"新"值获得下一个索引(1、2、3等),每个"相同"值获得与前一个"新"值相同的索引.运行始终以"new"开头,如果有>;1值,则后跟"ame".
请注意,情况并非如此.
data.frame(id = 1:13,
type = c("not_applicable",
"new",
"same",
"same",
"not_applicable",
"new",
"new",
"new",
"same",
"same",
"not_applicable",
"new",
"same"),
index = c(0, 1, 1, 1, 0, 2, 3, 4, 4, 4, 0, 5, 5))
我试过这个:
df0 %>%
mutate(index = with(rle(type != "not_applicable"),
rep(cumsum(values) * values, lengths)))
但它给了我以下输出:
id type index
1 1 not_applicable 0
2 2 new 1
3 3 same 1
4 4 same 1
5 5 not_applicable 0
6 6 new 2
7 7 new 2
8 8 new 2
9 9 same 2
10 10 same 2
11 11 not_applicable 0
12 12 new 3
13 13 same 3
我想 for each 以"new"开头的序列分配下一个索引.