簡體   English   中英

將數據轉換為時間序列

[英]transforming data into time series

我有一個csv數據集,我希望將其轉換為時間序列數據以進行時間序列分析。 數據看起來像這樣(有更多列,並且有17,190 obs。):

temp  interval

   10.0  2014-04-01 00:00:00

   10.0  2014-04-01 00:15:00

   10.0  2014-04-01 00:30:00

   10.0  2014-04-01 00:45:00

   7.8   2014-04-01 01:00:00

時間間隔POSIXct格式。

請將代碼轉換為時間序列的代碼對您有所幫助。

謝謝

CSV代表逗號分隔的值 問題中顯示的數據不是這種形式,但是如果我們假設該數據是在注釋末尾可重復顯示的數據幀DF ,則以下代碼給出了Zoo系列z並將其轉換為ts系列tt時間是自1970-01-01 00:00:00以來的秒數。 有關此功能的更多信息,請參見?read.zoo zoo程序包還包含帶有許多read.zoo示例的整個小插圖。

z可以用於繪圖,如果使用僅接受ts類輸入的函數,則tt可能有用。

library(zoo)
z <- read.zoo(DF, index = "interval", tz = "")
tt <- as.ts(z)

注意

Lines <- "
temp  interval
   10.0  2014-04-01 00:00:00
   10.0  2014-04-01 00:15:00
   10.0  2014-04-01 00:30:00
   10.0  2014-04-01 00:45:00
   7.8   2014-04-01 01:00:00"

# read into separate lines, trim whitespace from ends and
#  replace 2 or more consecutive spaces with comma
L <- gsub("  +", ",", trimws(readLines(textConnection(Lines))))
DF <- read.csv(text = L)

如果您在CSV與讀read_csvtidyverse您將自動獲得在POSIXct類的間隔柱。

dput如下:

library(tidyverse)

df <- structure(list(temp = c(10, 10, 10, 10, 7.8), interval = structure(c(1396310400, 
1396311300, 1396312200, 1396313100, 1396314000), class = c("POSIXct", 
"POSIXt"), tzone = "UTC")), class = c("spec_tbl_df", "tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -5L), spec = structure(list(
cols = list(temp = structure(list(), class = c("collector_double", 
"collector")), interval = structure(list(format = ""), class = c("collector_datetime", 
"collector"))), default = structure(list(), class = c("collector_guess", 
"collector")), skip = 1), class = "col_spec"))

您就可以重新排序cols並轉換為zoo。

library(zoo)

df <- df %>% 
  select(interval, temp) %>% 
  zoo()

class(df)
[1] "zoo"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM