rxtsreactivedygraphsr-dygraphs

Finding the maximum in an xts column within the last X hrs


I have a dataset within a reactive dygraph that looks like this:

data()$data.o

date data.o
2022-07-21 12:10 AM 400.1
2022-07-21 12:11 AM 33.9
2022-07-21 12:12 AM 32.5
2022-07-21 12:13 AM 35.1
2022-07-21 12:14 AM 31.5
2022-07-21 12:15 AM 39.5

I want to find the max value in the last 5 minutes so I can set my axis scale accordingly.

I've tried:

enddate = max(data()$date)
startdate = enddate - (60*5)
oMx <- max(datao.xts[startdate/enddate], na.rm = T)

But I get an error using datao.xts.

Is there a better way to go about this?

Edit:

Trying on a larger dataset for the last 480 minutes, returns -inf:

xts <- xts::xts(hvilleo, order.by = data()$date)
enddate <- end(xts) startdate <- enddate - (480-1) * 60
xts[paste0(startdate, enddate, sep = "/")] |> max(na.rm = TRUE) xts |>
utils::tail(480) |> max(na.rm =TRUE)

Solution

  • As far as I'm familiar with xts, your startdate/enddate part has simply to be a string, c.f. Joshua's response here. That's it.

    # allow me to create an xts object beforehand
    datetimes <- c("2022-07-21 12:10 AM",
                   "2022-07-21 12:11 AM",
                   "2022-07-21 12:12 AM",
                   "2022-07-21 12:13 AM",
                   "2022-07-21 12:14 AM",
                   "2022-07-21 12:15 AM") |> 
      strptime(format = "%Y-%m-%d %I:%M %p") |> 
      as.POSIXct()
    
    data <- c(400.1, 33.9, 32.5, 35.1, 31.5, 39.5)
    
    xts <- xts::xts(data, order.by = datetimes)
    
    # minor adjustments to your approach
    enddate <- end(xts)
    startdate <- enddate - (5-1) * 60
    
    xts[paste0(startdate, enddate, sep = "/")] |> max()
    #> [1] 39.5
    
    # assuming you are interested in the last five observations
    xts |> utils::tail(5) |> max()
    #> [1] 39.5