Muhammad D Vikar
Muhammad D Vikar

Reputation: 161

Conditional incrementation

I want to add a new column that contains a sequence number that increases if it matches the conditions of a particular column

Table1 <- tibble::tribble(~x, ~y,
                  "a",  1,
                  "b",  2,
                  "c",  2,
                  "d",  0,
                  "e",  1,
                  "f",  0,
                  "g",  0
)

Expected

x y RowGroup
a 1 1
b 2 2
c 2 3
d 0 3
e 1 4
f 0 4
g 0 4

I have got the solution with the following code, but the solution is done in 2 steps

Table1 <- Table1 %>% 
  mutate(RowGroup = if_else(!y == "0", cumsum(!y == "0"), NA_integer_)) %>% 
  fill(RowGroup, .direction = "down")

Is there a single step or specific function numbering from the tidyverse or some other package to achieve this?

Upvotes: 1

Views: 51

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

We could use cumsum and increment the sequence when y != 0.

library(dplyr)

Table1 %>% mutate(RowGroup = cumsum(y != 0))

#  x         y RowGroup
#  <chr> <dbl>    <int>
#1 a         1        1
#2 b         2        2
#3 c         2        3
#4 d         0        3
#5 e         1        4
#6 f         0        4
#7 g         0        4

Obviously, you could also directly achieve this without any packages.

Table1$RowGroup <- cumsum(Table1$y != 0)

Upvotes: 2

Related Questions