forked from renfrst/RTipsAndTricks
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRoundUpToQuarter.Rmd
41 lines (29 loc) · 914 Bytes
/
RoundUpToQuarter.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# *Round up* a date object to the latest quarter
It might be useful to *round up* a date to the quarter it is in.
Rounding to the current month or year is trivial, but it's tricky when we want
to round to the quarter.
The output is a date class object.
First, create a fake dataset.
```{r}
x <- c("2014-01-14", "2012-03-30", "2010-04-02", "2011-06-01", "2011-08-23", "2011-09-01", "2012-12-30", "2011-12-31")
x <- as.Date(x)
```
Next, create some intermediate, helper variables.
```{r}
yy <- year(x)
mm <- ceiling(month(x) / 3) * 3
dd <- ifelse(mm == 3, 31, ifelse(mm == 6, 30, ifelse(mm == 9, 30, ifelse(mm == 12, 31, NA))))
```
Then, `paste` the helper variables to a date class object.
```{r}
qtr <- as.Date(paste(yy, mm, dd, sep="-"))
```
Combine the vectors to a data frame.
```{r}
D <- data.frame(dateOriginal = x, dateQuarter = qtr)
```
Show the resulting date class object.
```{r}
str(D)
D
```