Loop to calculate maximum value

Asked

Viewed 126 times

0

I need to calculate the maximum consumption value based on the previous values each 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 don’t 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

2 answers

3

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

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

DICE.

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")

EDITION.
After seeing Willian Vieira’s reply I edited my reply with a new table dados. I do not know why, when I read the OP table not read it well.

2


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
  • Thank you very much!!

  • You’re welcome! If it was helpful, you can accept and validate the answer.

  • Sure! Sorry I’m new here, as I do to accept and validate your answers?

  • https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta

Browser other questions tagged

You are not signed in. Login or sign up in order to post.