For the sake of an exercice, I have to recreate the cummax
function in R using function()
and a for loop. The cummax
function calculates the cumulative maximum of its argument.
Thank you so much in advance
Here is what I tried to do until now:
x <- c(1,2,3,2,5,7,6,8,5)
my_cummax <- function(x) {
for (i in x){
if (x[i] > lag(x[i])){
print(x[i])
} else {
lag(x[i])
}
}
}
my_cummax(x)
CodePudding user response:
One way to do it would be as below:
x <- c(1,2,3,2,5,7,6,8,5)
my_cummax <- function(x) {
# preallocate the vector
out <- vector(mode = typeof(x), length = length(x))
# set the first element as current maximum
cur_max <- x[1]
for (i in seq_along(x)){
# if x[i] is larger than the current maximum use x[i] and update both out[i] and cur_max
if (x[i] > cur_max){
out[i] <- cur_max <- x[i]
# if x[i] is not larger than the current maximum use cur_max
} else {
out[i] <- cur_max
}
}
out
}
my_cummax(x)
#> [1] 1 2 3 3 5 7 7 8 8
# compare to:
cummax(x)
#> [1] 1 2 3 3 5 7 7 8 8
Created on 2022-10-12 by the reprex package (v2.0.1)