简体   繁体   English

将月份的最后一天发送到 R 中的 function

[英]Sending last day of month into a function in R

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 .可能这不是一个很好的方法,但我必须在过去 4 年中每个月的最后一天运行rbind并将所有日期的data.frame function

I already have my dataframe DF in my environment.我的环境中已经有我的 dataframe DF

MY FUNCTION我的 FUNCTION

Part 1 I need Dynamic Date Insertion here to loop over dates automatically.第 1 部分我需要在这里插入动态日期来自动循环日期。

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第2部分

Row Binding the output into one.将 output 绑定为一个。

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.可能有一些 package 可以做到这一点。

rbind output us as follow rbind output 我们如下

        date hc_cnt
1 2021-01-31   2946
2 2021-08-31   3039

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:要获取列出从 Date start到 Date end每月的最后一个日期的 Date 向量,仅使用基本 R ,您可以执行以下操作:

last_of_month <- function(start, end) {
  ## Replace "YYYY-MM-DD" with "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"

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)))]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM