【问题标题】:R Rounding a TimeR四舍五入
【发布时间】:2023-03-26 06:44:01
【问题描述】:

我有一个包含一系列时间的数据框,格式如下:

08:09:23.079

> class(timer3) 
[1] "factor"

我想将它们四舍五入/转换成这种格式:

08:09

最终目标是将它们用作绘图 x 轴的值,因此我认为它们需要采用某种类型的时间格式(动物园、as.Date 等)。

有什么建议吗?

【问题讨论】:

  • 两个步骤:1) 因子到字符:as.character() 2) 字符到 POSIXct:strptime()
  • 转成字符看strptime()
  • 你们中的某个人想在答案中评论您的评论,以便我可以选择它?
  • 你为什么不自己做呢?另一位版主已经拒绝了您之前的举报,说我们无法将 cmets 转换为您的答案。
  • @mweylandt:你能把你的评论放在答案中,这样我就可以选择了吗?

标签: r xts zoo


【解决方案1】:

假设我们有这个输入数据:

DF <- data.frame(times = c("08:09:23.079", "08:30:13.062"), values = 1:2)

为简单起见,我们假设每分钟最多有一个时间点(我们展示了一个在没有此限制的情况下稍长的替代方案):

library(zoo)
library(chron)

# this assumes we want to store times to the second
tt <- times(as.character(DF$times))
z <- zoo(DF$values, tt)

plot(z, xaxt = "n")

# custom axis - assumes sufficiently many points to get reasonable graph
# round tick mark locations to the minute and remove the seconds from label
axt <- trunc(times(axTicks(1)), "min")
axis(1, at = axt, lab = sub(":..$", "", axt))

上面创建 z 的方法可以替换为这个。无论每分钟是否有超过一个点,它都会起作用,因为它将它们聚合到一分钟:

# with this z we will be store times to the minute
z <- read.zoo(DF, FUN = function(x) trunc(times(as.character(x)), "min"), 
      aggregate = mean)

编辑:绘图和截断。

【讨论】:

    【解决方案2】:

    冒着被称为死灵法师的风险,我会回答这个问题,因为我认为这种情况经常出现。

    如果您将时间序列数据转换为xts 格式,请按照以下步骤操作。这里要用到的函数是align.time

    > head(GBPJPY)
                        GBPJPY.Open GBPJPY.High GBPJPY.Low GBPJPY.Close
    2009-05-01 00:14:59     146.387     146.882    146.321      146.620
    2009-05-01 00:29:54     146.623     146.641    146.434      146.579
    2009-05-01 00:44:59     146.579     146.908    146.570      146.810
    2009-05-01 00:59:59     146.810     146.842    146.030      146.130
    2009-05-01 01:14:59     146.130     146.330    146.100      146.315
    2009-05-01 01:29:57     146.315     146.382    146.159      146.201
    > head(align.time(GBPJPY, 15*60))
                        GBPJPY.Open GBPJPY.High GBPJPY.Low GBPJPY.Close
    2009-05-01 00:15:00     146.387     146.882    146.321      146.620
    2009-05-01 00:30:00     146.623     146.641    146.434      146.579
    2009-05-01 00:45:00     146.579     146.908    146.570      146.810
    2009-05-01 01:00:00     146.810     146.842    146.030      146.130
    2009-05-01 01:15:00     146.130     146.330    146.100      146.315
    2009-05-01 01:30:00     146.315     146.382    146.159      146.201
    

    【讨论】:

      【解决方案3】:
      as.zoo(sapply(timer3,substring,1,5))
      or as.xts?
      

      也许查看更大的数据样本会有所帮助。

      【讨论】:

        【解决方案4】:

        两个步骤:1) 因子到字符:as.character() 2) 字符到 POSIXct:strptime()

        【讨论】:

          猜你喜欢
          • 2023-01-12
          • 2012-08-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-11-12
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多