Aggregate ISO weeks into months with a dataset containing just ISO weeks

date, r

Solution

When it is necessary to allocate a week to a single month, the rule for first week of the year might be applied, although ISO 8601 does not consider this case. (Wikipedia)

For example, the 5th week of 2007 belongs to February, because the Thursday of the 5th week was the 1st of February.

I am using `data.table` and `ISOweek` packages. See the example how to compute the month of the week. Then you can do any aggregation by month.

require(data.table)
require(ISOweek)

df2 <- data.table(Year = c("2007"), Week = c(1:12),
                  Measurement = c(rnorm(12, mean = 4, sd = 1)))

# Generate Thursday as year, week of the year, day of week according to ISO 8601
df2[, thursday_ISO := paste(Year, sprintf("W%02d", Week), 4, sep = "-")]

# Convert Thursday to date format
df2[, thursday_date := ISOweek2date(thursday_ISO)]

# Compute month
df2[, month := format(thursday_date, "%m")]
df2

Suggestion by Uwe to compute a year-month string.

# Compute year-month
df2[, yr_mon := format(ISOweek2date(sprintf("%s-W%02d-4", Year, Week)), "%Y-%m")]
df2

And finally you can do an aggregation to the new table or by adding median as a column.

df2[, median(Measurement), by = yr_mon]

df2[, median := median(Measurement), by = yr_mon]
df2

Problem

My data is in a dataframe which has a structure like this: ``` df2 <- data.frame(Year = c("2007"), Week = c(1:12), Measurement = c(rnorm(12, mean = 4, sd = 1))) ``` Unfortunately I do not have the complete date (e.g. days are missing) for each measurement, only the Year and the Weeks (these are ISO weeks). Now I want to aggregate the Median of a Month's worth of measurements (e.g. the weekly measurements per month of the specific year) into a new column, Months. I did not find a convenient way to do this without having the exact day of the measurements available. Any inputs are much appreciated!

Original source

Related problems