Loop to calculate the maximum value

0

I need to calculate the maximum consumption value based on the previous values every time I loop the consumption data. For example on day 4, the maximum consumption would be calculated from day 1 to 4.

Follow the code I thought, but I do not know how it can be calculated

Maxconsumo<-c()

for (i in 1:length(Consumo)) {
  Maxconsumo <- .........
}

    Dia Consumo
    1   245
    2   256
    3   300
    4   450
    5   245
    6   256
    7   300
    8   450
    
asked by anonymous 24.10.2017 / 17:29

2 answers

1
Maxconsumo<-c()

Dia = 1:8
Consumo = c(245, 256, 300, 450, 245, 256, 300, 450)
data <- data.frame(Dia, Consumo)

for (i in 1:length(Consumo)) {
  Maxconsumo[i] <- max(data$Consumo[1:i])
}

Maxconsumo
# [1] 245 256 300 450 450 450 450 450
    
24.10.2017 / 17:54
3

If you want a function similar to cumsum , but calculating the cumulative maximum, here it goes, but I used a different name than yours to be consistent with% base%.

cummax <- function(x){
    x[is.na(x)] <- -Inf
    m <- numeric(length(x))
    m[1] <- x[1]
    for(i in seq_along(x)[-1]){
        m[i] <- if(x[i] > m[i - 1]) x[i] else m[i - 1]
    }
    m
}

cummax(dados$Consumo)
#[1] 245 256 300 450 450 450 450 450

DATA.

dados <-
structure(list(Dia = 1:8, Consumo = c(245, 256, 300, 450, 245, 
256, 300, 450)), .Names = c("Dia", "Consumo"), row.names = c(NA, 
-8L), class = "data.frame")

EDITIONS.
After seeing the answer from Willian Vieira I edited my answer with a new R table. I do not know why, when I read the OP table I did not read it well.

    
24.10.2017 / 17:49