2017-03-06 175 views
0

我們有2個月的數據。日期格式如下:mm/dd/yyyy。我們希望有(每2周)4個時期:彙總日期到期間

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等

輸出例如: enter image description here

回答

0

您將需要將字符串轉換爲某種形式的日期。我使用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 
+0

它完美,謝謝您的幫助! – olive

0

直視strptime改變你的MM/DD/YYYY日期爲數字,然後分裂()應該是有幫助的,請在此Split time-series weekly in R一開始..

ž< - strptime(日期,「 %M /%d /%y「)的

0

另一種可能性是使用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]]) 
})