Wistar
Wistar

Reputation: 3790

r increment column value based on another column value

I have a datatable x like this

+----+---------------+-------+
| id |      arg      | value |
+----+---------------+-------+
|  1 | New Day       | NA    |
|  2 | Eat breakfast | 3     |
|  3 | Bike          | 45    |
|  4 | New Day       | 0     |
|  5 | Get coffee    | 1     |
|  6 | Exercise      | 15    |
|  7 | Get beer      | NA    |
|  8 | New Day       |       |
|  9 | Pet cat       |       |
+----+---------------+-------+

I would like to add an incrementing column for every day to get something like this

+----+---------------+-------+-----+
| id |      arg      | value | day |
+----+---------------+-------+-----+
|  1 | New Day       | NA    |   1 |
|  2 | Eat breakfast | 3     |   1 |
|  3 | Bike          | 45    |   1 |
|  4 | New Day       | 0     |   2 |
|  5 | Get coffee    | 1     |   2 |
|  6 | Exercise      | 15    |   2 |
|  7 | Get beer      | NA    |   2 |
|  8 | New Day       |       |   3 |
|  9 | Pet cat       |       |   3 |
+----+---------------+-------+-----+

I have tried this without much success

x$day <-0
x<-within(x, day<-ifelse(arg == "New day", day+1, day))

Upvotes: 1

Views: 647

Answers (1)

Wistar
Wistar

Reputation: 3790

As pointed by @A.Webb

cumsum(arg == "New day")

Upvotes: 1

Related Questions