Skip to content

Instantly share code, notes, and snippets.

@christophergandrud
Last active December 17, 2015 19:28
Show Gist options
  • Save christophergandrud/5660246 to your computer and use it in GitHub Desktop.
Save christophergandrud/5660246 to your computer and use it in GitHub Desktop.
A function for summing a variable across quarters
#' A function for summing a variable across quarters.
#'
#' @param data a data frame where the variables can be found.
#' @param Var a character string naming the variable to sum.
#' @param TimeVar a character string nameing the variable with the time variable. Note, must contain the month and the year.
#' @param NewVar a character string with the summed variable's name
#'
#' @return a data frame with Quarter and summed variable columns.
#' @importFrom plyr ddply
#' @export
quarter_sum <- function(data, Var, TimeVar, NewVar = NULL)
{
require(lubridate)
require(plyr)
data$Quarter <- quarter(data[, TimeVar], with_year = TRUE)
data <- data[, c("Quarter", Var)]
names(data) <- c("Quarter", "TempVar")
SumTemp <- ddply(data, .(Quarter), transform, SumVar = sum(TempVar))
SumTemp <- SumTemp[, c(1, 3)]
SumTemp <- SumTemp[!duplicated(SumTemp[, 1], SumTemp[, 2]), ]
if (!is.null(NewVar)){
names(SumTemp) <- c("Quarter", NewVar)
return(SumTemp)
} else
return(SumTemp)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment