2

I would like to increment a count that restarts from 1 when a condition in an existing column is met.

For example I have the following data frame:

df <- data.frame(x1 = c(10, 100, 200, 300, 87, 90, 45, 80), 
                 x2 = c("start", "a", "b", "c", "start", "k", "l", "o"))

I would like to create x3 that starts counting from 1 each time that x2 == "start".

The resulting data frame should look like this:

   x1    x2 x3
1  10 start  1
2 100     a  2
3 200     b  3
4 300     c  4
5  87 start  1
6  90     k  2
7  45     l  3
8  80     o  4

I'm guessing there are existing functions in R that give a general solution. Can anyone point me in the right direction?

2 Answers 2

Reset to default

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

7

Using base R:

df$x3 <- with(df, ave(x1, cumsum(x2 == 'start'), FUN = seq_along))

gives:

> df
   x1    x2 x3
1  10 start  1
2 100     a  2
3 200     b  3
4 300     c  4
5  87 start  1
6  90     k  2
7  45     l  3
8  80     o  4

Or with the dplyr or data.table packages:

library(dplyr)
df %>% 
  group_by(grp = cumsum(x2 == 'start')) %>% 
  mutate(x3 = row_number())

library(data.table)
# option 1
setDT(df)[, x3 := rowid(cumsum(x2 == 'start'))][]
# option 2
setDT(df)[, x3 := 1:.N, by = cumsum(x2 == 'start')][]
3
  • 1
    My solution with base R turned out to be quite similar to yours. So here is another variation: ave(1:nrow(df), cumsum(df$x2 == "start"), FUN = rank)
    – d.b
    Feb 28, 2017 at 20:17
  • how would you modify the code if I want an end instead in x2. e.g. end = 4, k = 1 instead of start = 1 Jul 19, 2018 at 2:25
  • @JervisChionh See the comment I posted under your question.
    – Jaap
    Jul 19, 2018 at 7:34
4

Here is another base R method:

df$x3 <- sequence(diff(c(which(df$x2 == "start"), nrow(df)+1)))

which returns

df
   x1    x2 x3
1  10 start  1
2 100     a  2
3 200     b  3
4 300     c  4
5  87 start  1
6  90     k  2
7  45     l  3
8  80     o  4

sequence takes an integer vector and returns counts from 1 to each of the vector entries. It is fed the length of each count using diff to calculate the difference of the positions of the start of each sequence. Because of this, we have to include the value of the position after the final row of the data.frame, nrow(df)+1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.