2016-11-21 70 views
0

我有一項任務可以對時間序列數據進行異常檢測。我有異常檢測的代碼,但我正在爲它準備數據。數據如下所示。爲異常檢測準備數據

timestampUtc 

2016-08-01 14:38:01, 2016-08-01 14:38:06, 2016-08-01 14:38:12, 2016-08-01 14:38:18, 2016-08-01 14:38:22, 2016-08-01 14:38:27, 2016-08-01 14:38:27, 2016-08-01 14:38:30, 2016-08-01 14:38:37, 2016-08-01 14:38:38, 2016-08-01 14:38:38, 2016-08-01 14:38:46, 2016-08-01 14:39:03, 2016-08-01 14:39:03, 2016-08-01 14:39:10, 2016-08-01 14:39:12, 2016-08-01 14:39:15, 2016-08-01 14:39:16, 2016-08-01 14:39:20, 2016-08-01 14:39:28 

首先我想在timestampUtc列中做秒零。接下來,我想創建一個表示count的列,並希望計算該特定分鐘的值的數量。例如,輸出應該是這樣的:

timestampUtc count 

2016-08-01 14:38:00 12, 2016-08-01 14:39:00 6, 2016-08-01 14:40:00 8 

回答

1

您可以使用as.POSIXct()轉換字符串爲日期,使用一些格式忽略秒,然後用table來概括:

timestampUtc <- c('2016-08-01 14:38:01', '2016-08-01 14:38:06', '2016-08-01 14:38:12', '2016-08-01 14:38:18', '2016-08-01 14:38:22', '2016-08-01 14:38:27', '2016-08-01 14:38:27', '2016-08-01 14:38:30', '2016-08-01 14:38:37', '2016-08-01 14:38:38', '2016-08-01 14:38:38', '2016-08-01 14:38:46', '2016-08-01 14:39:03', '2016-08-01 14:39:03', '2016-08-01 14:39:10', '2016-08-01 14:39:12', '2016-08-01 14:39:15', '2016-08-01 14:39:16', '2016-08-01 14:39:20', '2016-08-01 14:39:28') 
timestampUtc <- as.POSIXct(timestampUtc, format="%Y-%m-%d %H:%M", tz="UTC") 
table(timestampUtc) 
2016-08-01 14:38:00 2016-08-01 14:39:00 
       12     8 
1

假設你時間戳已經在POSIXt格式,您的時間戳的數據存儲在DF-

df$count <- 1 
df$timestamp <- format(df$timestamp, format = "%Y-%m-%d %H:%M") 
df <- aggregate(count ~ timestamp, data = df, FUN = sum) 
names(df) <- c("timestamp", "count") 
+0

我想你可以避免總結一堆,如果你只是使用:'df < - 聚合(計數〜時間戳,數據= df,樂趣=長度)' –

1

無論是cutseq種方法POSIXt類有breaks(或by)一個間隔選項:

timestampUtc <-scan(text="2016-08-01 14:38:01, 2016-08-01 14:38:06, 2016-08-01 14:38:12, 2016-08-01 14:38:18, 2016-08-01 14:38:22, 2016-08-01 14:38:27, 2016-08-01 14:38:27, 2016-08-01 14:38:30, 2016-08-01 14:38:37, 2016-08-01 14:38:38, 2016-08-01 14:38:38, 2016-08-01 14:38:46, 2016-08-01 14:39:03, 2016-08-01 14:39:03, 2016-08-01 14:39:10, 2016-08-01 14:39:12, 2016-08-01 14:39:15, 2016-08-01 14:39:16, 2016-08-01 14:39:20, 2016-08-01 14:39:28", 
         what="", sep=",") 
#Read 20 items 

table(cut(as.POSIXct(timestampUtc), breaks="min") ) 
#------------ 
2016-08-01 14:38:00 2016-08-01 14:39:00 
       12     8 

假如你想10周或15分鐘的間隔,它可能是「10分鐘」或「15分鐘」。迄今爲止的其他答案之一是在輸入階段刪除信息,我認爲這是一個值得懷疑的做法,但是code_is_entropy在傳遞到table的階段使用了format,其格式字符串較短。