0

Suppose we have the following data frame and we wish to find the maximum of column 'value' up to each row, i.e. the resulting new column should be c(4993, 4993, 5036, 5036, 5036). Of course I can write a loop for this, but just wondering is there a simple dplyr solution as loops can get tedious to read?

> myDf[1:5, ]
        time value
1 2018-01-03  4993
2 2018-01-15    52
3 2018-08-02  5036
4 2018-08-17  -162
5 2018-09-05  4806

Many thanks!

Min
  • 179
  • 9

1 Answers1

1

You might be looking for the built-in function cummax:

set.seed(641032)
x <- rnorm(10)
x
#>  [1]  0.91326263  1.29385203  1.39573077  0.02985411  0.11766056 -1.15891724
#>  [7] -1.02509101 -0.31448858 -0.06675214 -1.34341847
cummax(x)
#>  [1] 0.9132626 1.2938520 1.3957308 1.3957308 1.3957308 1.3957308 1.3957308
#>  [8] 1.3957308 1.3957308 1.3957308
Vincent
  • 15,809
  • 7
  • 37
  • 39