尝试:
> dd = data.frame(t(sapply(strsplit(as.character(ddf$Date), '/'), c)))
> dd = data.frame(sapply(dd, function(x) as.numeric(as.character(x))))
> names(dd) = c('month','date','year')
> dd$fiscal=1
> for(i in 2:nrow(dd)) dd$fiscal[i] = with(dd,ifelse(month[i]==6 & month[i-1]==3, fiscal[i-1]+1, fiscal[i-1]))
> dd
month date year fiscal
1 6 1 2010 1
2 6 1 2010 1
3 6 1 2010 1
4 9 1 2010 1
5 9 1 2010 1
6 9 1 2010 1
7 12 1 2010 1
8 12 1 2010 1
9 12 1 2010 1
10 3 1 2011 1
11 3 1 2011 1
12 3 1 2011 1
13 6 1 2011 2
14 6 1 2011 2
15 6 1 2011 2
16 9 1 2011 2
17 9 1 2011 2
18 9 1 2011 2
19 12 1 2011 2
20 12 1 2011 2
21 12 1 2011 2
22 3 1 2012 2
23 3 1 2012 2
24 3 1 2012 2
数据:
ddf = structure(list(Date = structure(c(5L, 5L, 5L, 7L, 7L, 7L, 1L,
1L, 1L, 3L, 3L, 3L, 6L, 6L, 6L, 8L, 8L, 8L, 2L, 2L, 2L, 4L, 4L,
4L), .Label = c("12/1/2010", "12/1/2011", "3/1/2011", "3/1/2012",
"6/1/2010", "6/1/2011", "9/1/2010", "9/1/2011"), class = "factor")), .Names = "Date", class = "data.frame", row.names = c(NA,
-24L))
ddf
Date
1 6/1/2010
2 6/1/2010
3 6/1/2010
4 9/1/2010
5 9/1/2010
6 9/1/2010
7 12/1/2010
8 12/1/2010
9 12/1/2010
10 3/1/2011
11 3/1/2011
12 3/1/2011
13 6/1/2011
14 6/1/2011
15 6/1/2011
16 9/1/2011
17 9/1/2011
18 9/1/2011
19 12/1/2011
20 12/1/2011
21 12/1/2011
22 3/1/2012
23 3/1/2012
24 3/1/2012
两者可以绑定在一起,也可以添加四分之一:
dd2= cbind(ddf, dd)
dd2$quarter = dd2$month/3 -1
dd2$quarter = with(dd2, ifelse(quarter==0, 4, quarter))
dd2
Date month date year fiscal quarter
1 6/1/2010 6 1 2010 1 1
2 6/1/2010 6 1 2010 1 1
3 6/1/2010 6 1 2010 1 1
4 9/1/2010 9 1 2010 1 2
5 9/1/2010 9 1 2010 1 2
6 9/1/2010 9 1 2010 1 2
7 12/1/2010 12 1 2010 1 3
8 12/1/2010 12 1 2010 1 3
9 12/1/2010 12 1 2010 1 3
10 3/1/2011 3 1 2011 1 4
11 3/1/2011 3 1 2011 1 4
12 3/1/2011 3 1 2011 1 4
13 6/1/2011 6 1 2011 2 1
14 6/1/2011 6 1 2011 2 1
15 6/1/2011 6 1 2011 2 1
16 9/1/2011 9 1 2011 2 2
17 9/1/2011 9 1 2011 2 2
18 9/1/2011 9 1 2011 2 2
19 12/1/2011 12 1 2011 2 3
20 12/1/2011 12 1 2011 2 3
21 12/1/2011 12 1 2011 2 3
22 3/1/2012 3 1 2012 2 4
23 3/1/2012 3 1 2012 2 4
24 3/1/2012 3 1 2012 2 4