-1

I have a data frame with the following values

street  date    counts
A   2011-01-07  4
B   2011-01-07  2
A   2011-01-08  2
B   2011-01-08  6

I want the previous counts by date to be added with the new counts this is the output that I require how could I achieve this in R using dplyr or other libraries.

street  date    counts
A   2011-01-07  4
B   2011-01-07  2
A   2011-01-08  6
B   2011-01-08  8
Bippan Kumar
  • 507
  • 1
  • 6
  • 10

1 Answers1

2

You could try

library(dplyr)

df %>% group_by(street) %>% mutate(counts = cumsum(counts))

#> # A tibble: 4 x 3
#> # Groups:   street [2]
#>   street date       counts
#>   <fct>  <fct>       <int>
#> 1 A      2011-01-07      4
#> 2 B      2011-01-07      2
#> 3 A      2011-01-08      6
#> 4 B      2011-01-08      8

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87