0

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 )
Dharman
  • 30,962
  • 25
  • 85
  • 135
stats_noob
  • 5,401
  • 4
  • 27
  • 83

2 Answers2

1

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 )
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

Slightly modifying Ronak Shah's code:

#first variable
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 )

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

#combine - not a very efficient way to solve this

a = data.frame(a)
b = data.frame(b)
c = cbind(a,b)
Dharman
  • 30,962
  • 25
  • 85
  • 135