質問

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')

他のヒント

There might be more elegant solutions but this should work -

df1$date2 <- as.Date(
   paste(
      ifelse(
         strftime(df1$date1,'%m') == 12,  
         as.integer(strftime(df1$date1,'%Y')) + 1,
         as.integer(strftime(df1$date1,'%Y'))
      ),
      ifelse(
         strftime(df1$date1,'%m') == 12,  
         1,
         as.integer(strftime(df1$date1,'%m')) + 1
      ),
      1,
      sep = "-"
   ),
"%Y-%m-%d"
)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top