Hi srini,
First of all, it would be nice if you could provide the data as code, then people save some time and don't have to build the data frame first.
I used the package lubridate.
# Building data frame
library(lubridate)
set_date <- function(date){
as.Date(date, format = "%Y-%m-%d")
}
df <- tibble(
test_date = c(set_date("2016-09-01"), set_date("2016-10-01"), set_date("2016-03-01"), set_date("2016-03-01")),
subject = c("maths", "physics", "maths", "maths"),
grade = c(4,5,5,4)
)
I usually use a helper data frame for such operations, which might be slow with big data sets. Maybe there is a better way how to do this in a single mutate() statement. Anyway this should work:
# Function definition
add_counting <- function(df, date_col, subject_col){
d <- enquo(date_col)
s <- enquo(subject_col)
helper_df <- df %>% mutate(!!d := !!d %m+% months(6)) %>% #add 6 months to the date
group_by(!!d, !!s) %>% summarise(count = n())
df %>% left_join(helper_df, by = c(quo_name(d),quo_name(s)))
}
add_counting(df, test_date, subject)