Last active
December 17, 2015 19:28
-
-
Save christophergandrud/5660246 to your computer and use it in GitHub Desktop.
A function for summing a variable across quarters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#' 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