Home > Software design >  Is there a way to use a variable to get the last X observations of an XTS dataframe in R?
Is there a way to use a variable to get the last X observations of an XTS dataframe in R?

Time:10-26

I'm trying to average the last X minutes of a dataset using a variable in R, I also do not know how to set my start date to today at midnight, so I've just plugged in 24 hrs from the enddate instead:

xts <- xts::xts(tempdat, order.by = data()$date)
    enddate <- end(xts)
    todaydate <- enddate - 86400 (I'm not sure how to get today's date here at midnight)
    todaymins <- difftime(enddate, todaydate, units="hours")
    lastavg <- xts |> utils::tail(todayhrs) |> mean(na.rm =TRUE)

Running this, I get

Warning: Error in ==: comparison of these types is not implemented

  101: Summary.difftime
  100: tail.zoo
   97: ::

CodePudding user response:

Use last() on your xts object. It can be the last n observations or the last period of time as a character string.

library(xts)
data(sample_matrix)
x <- as.xts(sample_matrix)
last(x, 3)
##                Open     High      Low    Close
## 2007-06-28 47.67604 47.70460 47.57241 47.60716
## 2007-06-29 47.63629 47.77563 47.61733 47.66471
## 2007-06-30 47.67468 47.94127 47.67468 47.76719
last(x, "1 week")
##                Open     High      Low    Close
## 2007-06-25 47.20471 47.42772 47.13405 47.42772
## 2007-06-26 47.44300 47.61611 47.44300 47.61611
## 2007-06-27 47.62323 47.71673 47.60015 47.62769
## 2007-06-28 47.67604 47.70460 47.57241 47.60716
## 2007-06-29 47.63629 47.77563 47.61733 47.66471
## 2007-06-30 47.67468 47.94127 47.67468 47.76719

You can subset using an IS08601 string to get everything in a range (potentially open-ended on the left or right).

x["2007-06-27/"]
## 2007-06-27 47.62323 47.71673 47.60015 47.62769
## 2007-06-28 47.67604 47.70460 47.57241 47.60716
## 2007-06-29 47.63629 47.77563 47.61733 47.66471
## 2007-06-30 47.67468 47.94127 47.67468 47.76719
  •  Tags:  
  • rxts
  • Related