有条件地查找xts数据集的开始和结束时间索引

问题描述 投票:0回答:2

我正在尝试为所有标签分别提取开始时间索引和结束时间索引,并分别存储它们。

编辑

根据评论的建议,我准备了一个示例数据集

data <- rnorm(11)

dates1 <- as.POSIXct("2019-03-18 10:30:00", tz = "CET") + 0:6*60
dates2 <- as.POSIXct("2019-03-19 08:30:00", tz = "CET") + 0:3*60
dates <- append(dates1, dates2)

R <- xts(x = data, order.by = dates) 
colnames(R) <- "R"
R$Label[1:7] <- 1
R$Label[8:11] <- 2

输出:

                           R Label
2019-03-18 10:30:00  1.193363635     1
2019-03-18 10:31:00 -0.558021057     1
2019-03-18 10:32:00  0.670440862     1
2019-03-18 10:33:00  0.073794492     1
2019-03-18 10:34:00 -0.416108940     1
2019-03-18 10:35:00 -0.596981420     1
2019-03-18 10:36:00  0.002006772     1
2019-03-19 08:30:00 -1.245200719     2
2019-03-19 08:31:00  0.417944923     2
2019-03-19 08:32:00  1.699169683     2
2019-03-19 08:33:00  0.861448103     2

R类是xts,动物园。

现在,我想分别存储标签1和标签2的开始和结束时间索引。我拥有更多带有更多标签的数据,因此需要将其自动化。如果您能提供帮助,我将不胜感激。谢谢

r timestamp xts
2个回答
0
投票

如果将其拆分为多个组件,然后在每个组件上使用startend,我们可以获得每个组的开始时间和结束时间。

s <- split(R, R$Label)
do.call("c", lapply(s, start)) # start of each group
do.call("c", lapply(s, end)) # end of each group

如果要行号代替执行相同的操作,但是将索引更改为1、2、3,...

R2 <- zoo(coredata(R))
s <- split(R2, R2$Label)
do.call("c", lapply(s, start)) # start of each group
do.call("c", lapply(s, end)) # end of each group

0
投票

使用您发布的数据:

library(xts)
library(dplyr)
library(tibble)
set.seed(42)

data <- rnorm(11)
dates1 <- as.POSIXct("2019-03-18 10:30:00", tz = "CET") + 0:6*60
dates2 <- as.POSIXct("2019-03-19 08:30:00", tz = "CET") + 0:3*60
dates <- append(dates1, dates2)

R <- xts(x = data, order.by = dates) 
colnames(R) <- "R"

R$Label <- 1        # note I have removed the indexing here
R$Label[8:11] <- 2

R %>% 
  as.data.frame() %>% 
  rownames_to_column() %>% 
  group_by(Label) %>% 
  summarise(min = min(rowname), max = max(rowname) )

# A tibble: 2 x 3
  Label min                 max                
  <dbl> <chr>               <chr>              
1     1 2019-03-18 09:30:00 2019-03-18 09:36:00
2     2 2019-03-19 07:30:00 2019-03-19 07:33:00
© www.soinside.com 2019 - 2024. All rights reserved.