如何使用自己的函数从时间序列的POSIXct元素中提取日期和时间?

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

关于此问题的跟进问题:How do I create a function that defines a moving threshold along local maxima in R?

我想将函数应用于时间序列,因此尝试了ThomasIsCoding针对“ xts”对象的解决方案。不幸的是,将其保存为数组不会提供值的日期/时间。有没有简单的方法将此添加到函数?xts-object看起来像这样:

str(ts_1)
An ‘xts’ object on 2018-04-30 23:30:00/2018-08-01 23:30:00 containing:
  Data: num [1:94, 1] 21695 21655 21679 21660 21662 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr "measured values"
  Indexed by objects of class: [POSIXct,POSIXt] TZ: UTC
  xts Attributes:  
 NULL

我相应地更改了功能:

growthfun<-function (a) {
  r <- c()
  s <- c()
  for (i in seq_along(a)) {
    if (a[i] >= max(a[1:(i-1)])) {
      r <- c(r, as.POSIXct(index(a[i])))
      s <- c(s, a[i])
    }
    else {
      next
    }
  }
  data.frame(row.names=r,s)
}

哪个给:

growthfun(ts_1)
               s
1525131000 21695
1525649400 21722
1525908600 21749
1525995000 21769
1526081400 21788
1526340600 21809

前6个元素。我不知道为什么索引的日期/时间没有以POSIXct格式带入数组,而是转换为这些长数字元素。如果完全需要,我可以尝试提供一个可重现的示例,但是它采取了一些步骤来获取时间序列,因此,如果不在此处放置大量文本和代码,就看不到一种优雅的方法。感谢您的帮助。

r function time-series posixct
1个回答
0
投票

将自1970年1月1日以来的秒转换为日期/时间。

growthfun<-function (a) {
  r <- c()
  s <- c()
  for (i in seq_along(a)) {
    if (a[i] >= max(a[1:(i-1)])) {
      r <- c(r, as.POSIXct(index(a[i])))
      s <- c(s, a[i])
    }
    else {
      next
    }
  }
  data.frame(row.names=as.POSIXct(r, origin = "1970-01-01", tz = ""), s)
}

growthfun(ts_1)
                           s
2020-04-20 22:31:28 50.13211
2020-04-20 22:44:05 50.23050
2020-04-20 22:53:49 50.42096

数据

ts_1 <- structure(c(50.1321122972067, 50.0355467742705, 49.9122834457642, 
49.9948860954217, 50.0397819115463, 50.2304961977954, 49.8852887132391, 
50.420955209067, 50.3734680543285, 50.2443255196795), .Dim = c(10L, 
1L), .Dimnames = list(NULL, NULL), index = structure(c(1587396688, 
1587396699, 1587396846, 1587397205, 1587397420, 1587397445, 1587397972, 
1587398029, 1587398179, 1587398337), tzone = "", tclass = c("POSIXct", 
"POSIXt")), class = c("xts", "zoo"), .CLASS = "double")

                        [,1]
2020-04-20 22:31:28 50.13211
2020-04-20 22:31:39 50.03555
2020-04-20 22:34:06 49.91228
2020-04-20 22:40:05 49.99489
2020-04-20 22:43:40 50.03978
2020-04-20 22:44:05 50.23050
2020-04-20 22:52:52 49.88529
2020-04-20 22:53:49 50.42096
2020-04-20 22:56:19 50.37347
2020-04-20 22:58:57 50.24433
© www.soinside.com 2019 - 2024. All rights reserved.