My data is in a data.frame format like this sample data:
data <-
structure(list(Article = structure(c(1L, 1L, 3L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L
I thought I would provide a dplyr
-esque solution.
expand.grid()
to generate the pair-wise combinations you are looking for. left_join()
to join in the demand data (filling the rest with NAs).full_data <- expand.grid(Article=data$Article,Week=data$Week)
out <- left_join(tbl_dt(full_data),data)
out[is.na(out)] <- 0 # fill with zeroes for summarise below.
Then as before:
WeekSums <- out %>%
group_by(Article, Week) %>%
summarise(
WeekDemand = sum(Demand)
)
If you use this transformation often then perhaps a convenience function:
xpand <- function(df, col1, col2,na_to_zero=TRUE){
require(dplyr)
# to substitute in the names "as is" need substitute then eval.
xpand_call <- substitute(
expanded <- df %>%
select(col1,col2) %>%
expand.grid()
)
eval(xpand_call)
out <- left_join(tbl_dt(expanded), df) # join in any other variables from df.
if(na_to_zero) out[is.na(out)] <- 0 # convert NAs to zeroes?
return(out)
}
This way you can do:
expanded_df <- xpand(df,Article,Week)