给我一个月所有日期列表的功能

时间:2019-05-30 07:07:16

标签: r function date

有没有可以列出指定月份(年)中所有日期的功能

即:

proper_function("January",2019)

结果是

 [1] "2019-01-01" "2019-01-02" "2019-01-03" "2019-01-04" "2019-01-05" "2019-01-06" "2019-01-07"
 [8] "2019-01-08" "2019-01-09" "2019-01-10" "2019-01-11" "2019-01-12" "2019-01-13" "2019-01-14"
[15] "2019-01-15" "2019-01-16" "2019-01-17" "2019-01-18" "2019-01-19" "2019-01-20" "2019-01-21"
[22] "2019-01-22" "2019-01-23" "2019-01-24" "2019-01-25" "2019-01-26" "2019-01-27" "2019-01-28"
[29] "2019-01-29" "2019-01-30" "2019-01-31"

我可以编写一个简单的程序,因为除了2月,每个月都有固定的日期,但是我想某些基本软件包中应该存在一些功能

2 个答案:

答案 0 :(得分:4)

写一个应该不难。仅使用基数R就可以做到

proper_function <- function(month, year) {
   start <- as.Date(paste0("01", month,year), "%d%B%Y")
   end <- seq(start, length.out = 2, by = "month")[2]
   seq(start, end - 1, by  = "day")
}

proper_function("June",2019)
# [1] "2019-06-01" "2019-06-02" "2019-06-03" "2019-06-04" "2019-06-05"....  
#     "2019-06-25" "2019-06-26" "2019-06-27" "2019-06-28" "2019-06-29" "2019-06-30"

proper_function("February",2019)
#[1] "2019-02-01" "2019-02-02" "2019-02-03" "2019-02-04" "2019-02-05" ....
#    "2019-02-25" "2019-02-26" "2019-02-27" "2019-02-28"

您可以确定输入要采用的格式,并相应地更改format中的as.Date选项。

答案 1 :(得分:3)

您可以使用lubridate软件包。您只需要以以下格式提供月份:

proper_function <- function(x) {
  x <- as_date(x)
  y <- days_in_month(x)
  as_date(1:y, origin = x-1)
}
x <- c("2012-02-01")
proper_function(x)
 [1] "2012-02-01" "2012-02-02" "2012-02-03" "2012-02-04" "2012-02-05" "2012-02-06" "2012-02-07" "2012-02-08"
 [9] "2012-02-09" "2012-02-10" "2012-02-11" "2012-02-12" "2012-02-13" "2012-02-14" "2012-02-15" "2012-02-16"
[17] "2012-02-17" "2012-02-18" "2012-02-19" "2012-02-20" "2012-02-21" "2012-02-22" "2012-02-23" "2012-02-24"
[25] "2012-02-25" "2012-02-26" "2012-02-27" "2012-02-28" "2012-02-29"