以下是数据:

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"开头,如果有&gt;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"开头的序列分配下一个索引.

推荐答案

你可以接受cumsum美元的帮助-

library(dplyr)

df0 %>%
  mutate(index = cumsum(type == "new"), 
         index = replace(index, type == "not_applicable", 0))

#   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     3
#8   8            new     4
#9   9           same     4
#10 10           same     4
#11 11 not_applicable     0
#12 12            new     5
#13 13           same     5

R相关问答推荐

如何在ggplot 2 geom_segment图表中将UTC转换为EET?

如何使用geom_sf在边界显示两种 colored颜色 ?

如何求解arg必须为NULL或deSolve包的ode函数中的字符向量错误

在发布到PowerBI Service时,是否可以使用R脚本作为PowerBI的数据源?

任意列的欧几里得距离

警告:lmdif:info = 0. nls. lm()函数的输入参数不正确

如何在xyplot中 for each 面板打印R^2

如何直接从R中的风险分数计算c指数?

如何在geom_col中反转条

删除具有相同标题的tabPanel(shinly)

制作等距离的线串副本

使用较长的查询提取具有部分匹配的列表中的较短目标,

您是否可以将组添加到堆叠的柱状图

基于数据集属性将科分配给物种

观察器中的inaliateLater的位置

有没有办法一次粘贴所有列

在散点图中使用geom_point放置线图例

按组和连续id计算日期差

在ggplot2图表中通过端点连接点

使用同一行中的前一个值填充R矩阵中的缺失值