May be this isn't a nice way to do this but I have to run over every last day of month into a function
for last 4 years and rbind
the output of all the dates into one data.frame
.
I already have my dataframe DF
in my environment.
MY FUNCTION
Part 1 I need Dynamic Date Insertion here to loop over dates automatically.
myfunct <- function (date) {
abc <- subset(DF, HIRE_DATE <= date || LAST_WORKING_DATE <= date )
abc <- subset(abc, TDATE <= date)
augact <- abc %>%
group_by(ID_Merged) %>%
slice(which.max(TDATE))
augact <- subset(augact, ASSIGNMENT_STATUS == "ACTIVE")
hc_cnt <- nrow(augact)
x <- data.frame(date, hc_cnt)
return(x)
}
Part 2
Row Binding the output into one.
x <- myfunct("2021-01-31")
y <- myfunct("2021-08-31")
dfmerged <- rbind(x,y)
Please remember I want to automatically send the last day of the every month. May be there's some package that can do this.
rbind output us as follow
date hc_cnt
1 2021-01-31 2946
2 2021-08-31 3039
CodePudding user response:
I meant this as a comment, but since it is really another answer, it should be visible...
To obtain a Date vector listing the last date of each month from Date start
to Date end
, using base R only, you can do:
last_of_month <- function(start, end) {
## Round "YYYY-MM-DD" down to "YYYY-MM-01"
start <- as.Date(format(start, "%Y-%m-01"))
seq(start, end 1, by = "1 month")[-1L] - 1
}
last_of_month(as.Date("2020-01-15"), as.Date("2021-11-18"))
# [1] "2020-01-31" "2020-02-29" "2020-03-31" "2020-04-30" "2020-05-31"
# [6] "2020-06-30" "2020-07-31" "2020-08-31" "2020-09-30" "2020-10-31"
# [11] "2020-11-30" "2020-12-31" "2021-01-31" "2021-02-28" "2021-03-31"
# [16] "2021-04-30" "2021-05-31" "2021-06-30" "2021-07-31" "2021-08-31"
# [21] "2021-09-30" "2021-10-31"
CodePudding user response:
May be I can help you. You can get list of all ends of months by hand:
library(data.table)
date_start <- as.Date("2020-01-01")
date_end <- Sys.Date()
all_dates <- .Date(date_start:date_end)
ends_of_months <- all_dates[which(month(all_dates) != month(lead(all_dates)))]