[英]How to create variables in a dataframe as there are days between two dates?
[英]Create a Vector of All Days Between Two Dates
R 中是否有一種簡單的方法可以逐項列出兩個指定日期之間發生的所有有效日期? 例如,我想要以下輸入:
itemizeDates(startDate="12-30-11", endDate="1-4-12")
生成以下日期:
"12-30-11" "12-31-11", "1-1-12", "1-2-12", "1-3-12", "1-4-12"
我對日期的課程和格式很靈活,我只需要一個概念的實現。
你正在尋找seq
> seq(as.Date("2011-12-30"), as.Date("2012-01-04"), by="days")
[1] "2011-12-30" "2011-12-31" "2012-01-01" "2012-01-02" "2012-01-03"
[6] "2012-01-04"
或者,您可以使用:
> as.Date(as.Date("2011-12-30"):as.Date("2012-01-04"), origin="1970-01-01")
[1] "2011-12-30" "2011-12-31" "2012-01-01" "2012-01-02" "2012-01-03"
[6] "2012-01-04"
請注意:
“非數字參數在內部強制”。 因此,我們轉換回類Date
,使用類“數字”的as.Date
方法並提供origin
。
這是滿足您特定要求的功能
itemizeDates <- function(startDate="12-30-11", endDate="1-4-12",
format="%m-%d-%y") {
out <- seq(as.Date(startDate, format=format),
as.Date(endDate, format=format), by="days")
format(out, format)
}
> itemizeDates(startDate="12-30-11", endDate="1-4-12")
[1] "12-30-11" "12-31-11" "01-01-12" "01-02-12" "01-03-12" "01-04-12"
我更喜歡使用 lubridate 包來解決日期時間問題。 一旦你知道它就更直觀,更容易理解和使用。
library(lubridate)
#mdy() in lubridate package means "month-day-year", which is used to convert
#the string to date object
>start_date <- mdy("12-30-11")
>end_date <- mdy("1-4-12")
#calculate how many days in this time interval
>n_days <- interval(start_date,end_date)/days(1)
>start_date + days(0:n_days)
[1]"2011-12-30" "2011-12-31" "2012-01-01" "2012-01-02" "2012-01-03" "2012-01-04"
#convert to original format
format(start_date + days(0:n_days), format="%m-%d-%y")
[1] "12-30-11" "12-31-11" "01-01-12" "01-02-12" "01-03-12" "01-04-12"
lubridate
中的 2 個類似實現:
library(lubridate)
as_date(mdy("12-30-11"):mdy("1-4-12"))
# OR
seq(mdy("12-30-11"), mdy("1-4-12"), by = "days")
這些不會將您的日期格式化為月-日-年,但您可以根據需要修復格式。 但是在分析時,年-月-日有點容易處理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.