I'm trying to do some tests around measurement periods in time. I'd like to increment the size of the measurement bins (ie 1 month vs 2 months, etc.).
I have a data frame with a date seq() which works fine my problem is with incrementing the date by a month, week, etc.
df1 <- data.frame(id = 1:20, date1 = seq(as.Date('2012-01-01'),by = 'month', len = 20))
df1$date2 <- df1$date1 + 30
This is obviously wrong if I want the 1st of each month or week. Is there a function or package for this type of issue?
EDIT:
This :
seq( x, by = "month", length.out = 1)
seems to work for individual cells, but won't work for a column as it returns a numeric:
df1$date2 <- sapply(df1$date1, function(x) seq( x, by = "month", length.out = 1))
> head(df1)
id date1 date2
1 1 2012-01-01 15340
2 2 2012-02-01 15371
3 3 2012-03-01 15400
4 4 2012-04-01 15431
5 5 2012-05-01 15461
6 6 2012-06-01 15492
It sounds like you're looking for cut
:
df1$date2 <- cut(df1$date1 + as.difftime(31, units='days'), breaks='months')
df1$date3 <- cut(df1$date2 + as.difftime(1, units='weeks'), breaks='weeks')