Vasim
Vasim

Reputation: 3143

No of monthly days between two dates

diff(seq(as.Date("2016-12-21"), as.Date("2017-04-05"), by="month"))
Time differences in days
[1] 31 31 28

The above code generates no of days in the month Dec, Jan and Feb. However, my requirement is as follows

#Results that I need
#monthly days from date 2016-12-21 to 2017-04-05 
11, 31, 28, 31, 5
#i.e 11 days of Dec, 31 of Jan, 28 of Feb, 31 of Mar and 5 days of Apr.

I even tried days_in_month from lubridate but not able to achieve the result

library(lubridate)    
days_in_month(c(as.Date("2016-12-21"), as.Date("2017-04-05")))
Dec Apr 
 31  30 

Upvotes: 0

Views: 95

Answers (2)

Uwe
Uwe

Reputation: 42544

Although we have seen a clever replacement of table by rle and a pure table solution, I want to add two approaches using grouping. All approaches have in common that they create a sequence of days between the two given dates and aggregate by month but in different ways.

aggregate()

This one uses base R:

# create sequence of days
days <- seq(as.Date("2016-12-21"), as.Date("2017-04-05"), by = 1)
# aggregate by month
aggregate(days, list(month = format(days, "%b")), length)
#  month  x
#1   Apr  5
#2   Dez 11
#3   Feb 28
#4   Jan 31
#5   Mrz 31

Unfortunately, the months are ordered alphabetically as it happened with the simple table() approach. In these situations, I do prefer the ISO8601 way of unambiguously naming the months:

aggregate(days, list(month = format(days, "%Y-%m")), length)
#    month  x
#1 2016-12 11
#2 2017-01 31
#3 2017-02 28
#4 2017-03 31
#5 2017-04  5

data.table

Now that I've got used to the data.table syntax, this is my preferred approach:

library(data.table)
data.table(days)[, .N, .(month = format(days, "%b"))]
#   month  N
#1:   Dez 11
#2:   Jan 31
#3:   Feb 28
#4:   Mrz 31
#5:   Apr  5

The order of months is kept as they have appeared in the input vector.

Upvotes: 1

sirallen
sirallen

Reputation: 1966

Try this:

x = rle(format(seq(as.Date("2016-12-21"), as.Date("2017-04-05"), by=1), '%b'))

> setNames(x$lengths, x$values)
# Dec Jan Feb Mar Apr 
#  11  31  28  31   5 

Upvotes: 3

Related Questions