簡體   English   中英

將日期匯總為期間

[英]Aggregate dates into periods

我們有2個月的數據。 日期采用以下格式:mm / dd / yyyy。 我們希望有4個周期(每2周):

Period1: 06/01/15 - 06/15/15
Period2: 06/16/15 - 06/30/15
Period3: 07/01/15 - 07/15/15
Period4: 07/16/15 - 07/31/15

這樣,我們想向數據集中添加4個額外的虛擬列,即Period1,Period2等。

輸出示例: 在此處輸入圖片說明

您將需要將字符串轉換為某種日期形式。 我使用POSIXct 之后,您可以使用cut將日期分成幾組。 從組中,您可以使用model.matrix創建虛擬變量。 我添加了更多測試日期以更好地說明結果。

Breaks = as.POSIXct(c("06/01/15", "06/16/15", "07/01/15",
    "07/16/15", "08/01/15"), format="%m/%d/%y")

TestData = c("06/15/15", "06/13/15", "06/20/15", "07/17/15")
Periods  = cut(as.POSIXct(TestData, format="%m/%d/%y"), breaks=Breaks)
as.numeric(Periods)
[1] 1 1 2 4

Dummies = model.matrix(~ Periods - 1)
  Periods2015-06-01 Periods2015-06-16 Periods2015-07-01 Periods2015-07-16
1                 1                 0                 0                 0
2                 1                 0                 0                 0
3                 0                 1                 0                 0
4                 0                 0                 0                 1

Result = data.frame(TestData, Dummies)
names(Result) = c("Date", "Period1", "Period2", "Period3", "Period4")
Result
      Date Period1 Period2 Period3 Period4
1 06/15/15       1       0       0       0
2 06/13/15       1       0       0       0
3 06/20/15       0       1       0       0
4 07/17/15       0       0       0       1

查看strptime將您的mm / dd / yyyy日期轉換為數字,然后split()應該會有所幫助,請在R中每周檢查一次此Split time-series

z <-strptime(Date,“%m /%d /%y”)

另一種可能性是使用lubridate

 library(lubridate)

 Period1 <- interval(start = mdy("06/01/15"), end = mdy("06/15/15"))
 Period2 <- interval(start = mdy("06/16/15"), end = mdy("06/30/15"))
 Period3 <- interval(start = mdy("07/01/15"), end = mdy("07/15/15"))
 Period4 <- interval(start = mdy("07/16/15"), end = mdy("07/31/15"))

 Period <- list(Period1, Period2, Period3, Period4)

 TestData <- mdy(c("06/15/15", "06/13/15", "06/20/15", "07/17/15"))

 sapply(1:length(TestData), function(x){
   as.numeric(TestData %within% Period[[x]])
 })

暫無
暫無

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

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