通过从xts对象中提取信息来创建数据框

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

这里是可复制的示例-

data <- rnorm(6)

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

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

输出:

2019-03-18 10:30:00  0.8303556     1
2019-03-18 10:31:00 -1.5585603     1
2019-03-18 10:32:00 -0.1266884     1
2019-03-19 08:30:00  0.3562468     2
2019-03-19 08:31:00  1.0219780     2
2019-03-19 08:32:00  2.5127290     2

我正在尝试创建预期结果如下的数据框:

Label| start timestamp    |end timestamp      | start R  | end R 
1    | 2019-03-18 10:30:00|2019-03-18 10:32:00| 0.8303556|-0.1266884
.
.

您能帮忙吗?我可以分别称呼这些值,但不幸的是无法完全将它们放在一起。

enter image description here

r timestamp time-series xts
1个回答
0
投票

对于这样的操作,如果将数据转换为数据框然后执行操作,会更容易。

library(dplyr)
library(zoo)

R %>%
  fortify.zoo() %>%
  group_by(Label) %>%
  summarise_at(vars(Index, R), list(start = first, end = last))
© www.soinside.com 2019 - 2024. All rights reserved.