xts
Fill NA in a time series only to a limited number
Here’s another way: l <- cumsum(! is.na(x)) c(NA, x[! is.na(x)])[replace(l, ave(l, l, FUN=seq_along) > 4, 0) + 1] # [1] 1 1 1 1 5 5 5 5 NA NA 11 12 12 12 12 NA NA NA 19 20 edit: my previous answer required that x have no duplicates. The current answer does not. … Read more
Subset xts object by time of day
If your xts object is called x then something like y <- x[“T09:30/T11:00”] works for me to get a slice of the morning session, for example.
Rolling Sum by Another Variable in R
If your data is big, you might want to check out this solution which uses data.table. It is pretty fast. If you need more speed, you can always change mapply to mcmapply and use multiple cores. #Load data.table and convert to data.table object require(data.table) setDT(data)[,ID2:=.GRP,by=c(“ID”)] #Build reference table Ref <- data[,list(Compare_Value=list(I(USD)),Compare_Date=list(I(Date))), by=c(“ID2”)] #Use mapply to … Read more
Creating regular 15-minute time-series from irregular time-series
xts extends zoo, and zoo has extensive examples for this in its vignettes and documentation. Here is a worked example. I think I have done that more elegantly in the past, but this is all I am coming up with now: R> twohours <- ISOdatetime(2012,05,02,9,0,0) + seq(0:7)*15*60 R> twohours [1] “2012-05-02 09:15:00 GMT” “2012-05-02 09:30:00 … Read more
Convert data frame with date column to timeseries
Your DATE column may represent a date, but it is actually either a character, factor, integer, or a numeric vector. First, you need to convert the DATE column to a Date object. Then you can create an xts object from the CLOSE and DATE columns of your PRICE data.frame. Finally, you can use the xts … Read more
Return data subset time frames within another timeframes?
You can use the .index* family of functions to get certain months or certain days of the month. See ?index for the full list of functions. For example: library(quantmod) getSymbols(“SPY”) SPY[.indexmon(SPY)==0] # January for all years (note zero-based indexing!) SPY[.indexmday(SPY)==1] # The first of every month SPY[.indexwday(SPY)==1] # All Mondays
How to aggregate a dataframe by week?
In the tidyverse, df2 %>% group_by(week = week(time)) %>% summarise(value = mean(values)) ## # A tibble: 5 × 2 ## week value ## <dbl> <dbl> ## 1 8 37.50000 ## 2 9 38.57143 ## 3 10 38.57143 ## 4 11 36.42857 ## 5 12 45.00000 Or use isoweek instead: df2 %>% group_by(week = isoweek(time)) %>% … Read more