2017-03-06 144 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]]) 
})