Search code examples
rtime-seriesaggregatexts

Aggregate data by irregular time periods ("xts" library)


I am trying to follow this stack post over here: How to get sum of values every 8 days by date in data frame in R

Does anyone know why this doesn't work?

library(xts)

set.seed(123)
    

    property_damages_in_dollars <- rnorm(731,100,10)

    date_decision_made <- format(as.Date(date_decision_made), "%Y/%m/%d")
    
   other_damages_in_dollars <- rnorm(731,10,10)

final_data <- data.frame(date_decision_made, other_damages_in_dollars, property_damages_in_dollars)

    ep <- endpoints(final_data,'days',k=8)
    a = period.apply(x=final_data,ep,FUN=sum )

Note: for two variables, could this code work?

dat <- xts(cbind(final_data$property_damages_in_dollars, final_data$other_damages_in_dollars),
           as.Date(final_data$date_decision_made, '%Y/%m/%d'))
ep <- endpoints(dat,'days',k=8)
a = period.apply(x=dat,ep,FUN=sum )

Solution

  • You have a dataframe, change it to xts object.

    library(xts)
    
    dat <- xts(final_data$property_damages_in_dollars, 
               as.Date(final_data$date_decision_made, '%Y/%m/%d'))
    ep <- endpoints(dat,'days',k=8)
    a = period.apply(x=dat,ep,FUN=sum )