按不规则时间段聚合数据("xts" 库)

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

我正在尝试关注这里的堆栈 post:How to get sum of values every 8 days by date in data frame in R

有谁知道为什么这不起作用?

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 )

注意:对于两个变量,此代码是否可行?

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 )

您有一个数据框,将其更改为 xts 对象。

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 )

稍微修改

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