【问题标题】:Parsing timestamps takes a very long time解析时间戳需要很长时间
【发布时间】:2017-10-12 12:33:11
【问题描述】:

我编写了一个函数来制作一个矩阵,其中包含从纪元时间戳(以毫秒为单位)生成的年、月和日列。然而,这个函数非常慢,以至于它对我拥有的 7+ 百万行数据毫无用处。

有没有比这快得多的方法来将毫秒时间戳解析为年、月和日?

timestamp_to_ymd <- function(data){
  result <- matrix(nrow = length(data), ncol = 3)

  pb <- txtProgressBar(min = 0, max = length(data), style = 3)
  for (i in 1:length(data)){
    posixtime <- as.POSIXlt(data[i]/1000, origin="1970-01-01")

    result[i,1] <- posixtime$year + 1900
    result[i,2] <- posixtime$mon + 1
    result[i,3] <- posixtime$mday
    setTxtProgressBar(pb, i)
  }
  close(pb)
  return(result)
}

生成测试数据:

testdata <- 1483225200000:1483228200000

【问题讨论】:

  • 请查看特定于时间序列数据的包,例如zooxts

标签: r performance


【解决方案1】:

你不需要循环,那些函数可以处理向量:

result <- matrix(nrow = length(data), ncol = 3)
posixtime <- as.POSIXlt(data/1000, origin="1970-01-01")
result[,1] <- posixtime$year + 1900
result[,2] <- posixtime$mon + 1
result[,3] <- posixtime$mday
result

【讨论】:

  • 哦,是的,非常棒,他在几秒钟内就完成了这个功能!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-22
  • 2013-09-07
  • 2020-08-26
  • 2014-10-09
  • 2012-11-26
相关资源
最近更新 更多