1

I want to create a column with sequential values but it gets its value from input from two other columns in the df. I want the value to sequentially count if either Team changes (between 1 and 2) or Event = x. Any help would be appreciated! See example below:

    Team   Event   Value
1    1       a       1
2    1       a       1
3    2       a       2
4    2       x       3
5    2       a       3
6    1       a       4
7    1       x       5
8    1       a       5
9    2       x       6
10   2       a       6 

1 Answer 1

1

This will do it...

df$Value <- cumsum(df$Event=="x" | c(1, diff(df$Team))!=0)

It takes the cumulative sum (i.e. of TRUE values) of those elements where either Event=="x" or the difference in successive values of Team is non-zero. An extra element is added at the start of the diff term to keep it the same length as the original.

Sign up to request clarification or add additional context in comments.

1 Comment

That is more complex. It can be done, but it is probably best to ask as a new question and restore this question so that it makes sense - as it stands your example disagrees with your accepted answer, which is not very helpful to other readers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.