【问题标题】:Split xts object by events按事件拆分 xts 对象
【发布时间】:2013-04-13 10:18:22
【问题描述】:

我有一个带有少量事件指示器的 xts 对象。我需要将它按某些事件拆分,以便从给定事件到下一个事件的所有条目都将保存在相同的xts 中,最终创建一个xts 对象列表,每个对象都包含最后一个事件没有其他同类型事件的条目。

一个例子:

ts = as.Date(Sys.Date()-99:0)
e1 = numeric(100);e1[10*1:10]=1
e2 = numeric(100);e2[15*1:6]=1
y  = 1:100  # just a sample content
xs = as.xts(cbind(e1,e2,y),order.by=ts)

ee = e1*e2==1  # the event in which both e1 and e2 are 1, should happen at 30,60,90

# here should be splitting function that gets xs and ee as parameters
# and should return a list of 4 xts: the first with the entries 1 through 30, 
# the second with entries 31 to 60, the third with entries 61 to 90, and the last
# with entries 91 to 100

您的建议将不胜感激。

【问题讨论】:

    标签: r split xts


    【解决方案1】:

    使用cumsum(ee) 创建分组变量,然后调用split。您必须对cumsum 的输出做一个小的改动,因为您希望TRUE 值成为组中的最后一个观察值(而不是第一个)。

    split(xs, c(0,head(cumsum(ee),-1)))
    split(xs,rev(cumsum(rev(ee))))  # grouping factors reversed
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-25
      • 2015-10-08
      • 2019-07-19
      • 1970-01-01
      • 2014-04-12
      • 1970-01-01
      • 2016-06-02
      • 1970-01-01
      相关资源
      最近更新 更多