# Two different ways of calculating MAD return different solutions

I have a large dataframe data with following columns:

date        time        orig      new
2001-01-01  00:30:00    345       856
2001-01-01  00:32:43    4575      9261
2001-01-01  00:51:07    6453      2352
...
2001-01-01  23:57:51    421       168
2001-01-02  00:06:14    5612      3462
...
2001-01-31  23:49:11    14420     8992
2001-02-01  00:04:32    213       521
...


I want to calculate the monthly aggregated MAD, which can be calculated by $$\textrm{MAD} = \frac{\sum|\textrm{orig}-\textrm{new}|}{n}$$ where $$n$$ is the number of entries in one month. Ideally, at the end, I want the solutions (dataframe) in a following form:

month       mad
2001-01-01  7452.124
2001-02-01  3946.734
2001-03-01  995.938
...


I calculated the monthly MAD in two different ways.

Approach 1

I grouped data by month and took an average of the summed absolute differences (which is a "mathematical" way to do it, as I explained):

data %>%
group_by(
month = lubridate::floor_date(date, 'month')
) %>%


Approach 2

I grouped data by hour and got the MAD grouped by hour, and then re-grouped it by month and took an average. This is counter-intuitive, but I used the hourly grouped dataframe for other analyses and tried computing the monthly MAD from this dataframe directly.

data_grouped_by_hour <- data %>%
group_by(
day = lubridate::floor_date(date, 'day'),
hour = as.POSIXlt(time)\$hour
) %>%

data_grouped_by_hour %>%
group_by(
month = lubridate::floor_date(date, 'month')
) %>%


As hinted from the post title, these approaches return different values. I assume my first approach is correct, as it is more concise and follows the accurate concept, but I wonder why the second approach does not return the same value.

Any mathematical or programming explanation is appreciated.

• No idea about R, sorry, but does "month" meanly monthly date, e.g. December 2022, or month of year, e.g. December in any year? Commented Dec 13, 2022 at 13:07
• @NickCox monthly date, so December 2022, for example. In my data, I would see December 2001, December 2002, December 2003, and so on separately. Commented Dec 13, 2022 at 13:12
• That makes sense; I just wondered how the syntax worked here as it is surely ambiguous as read, although presumably documented clearly. Commented Dec 13, 2022 at 13:22