简体   繁体   中英

Function that give me all date list of a month

Is there a function that could list me all dates in a specified month(year)

that is:

proper_function("January",2019)

result is

 [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"

I could write a simple program since except for Feb each month has fixed dates for any year, but I suppose there should be some exist function in some basic packages

It should not be difficult to write one. Using only base R you can do

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"

You can decide the format your input is going to take and change the format option in as.Date accordingly.

You can use the lubridate package. You just have to provide the month in the following format:

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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