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

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