我正在开发一个函数来创建一个包含StartDate&的2列df。结束日期。我将提供3个参数:startdate,enddate,& interval,interval表示每行应代表我提供的范围内的不同日期,月份或年份。
例如,这个:
myfunction("2016/01/01", "2016/04/30", "months")
会产生与此相同的东西:
sd <- c("2016/01/01","2016/02/01","2016/03/01","2016/04/01")
ed <- c("2016/01/31","2016/02/29","2016/03/31","2016/04/30")
df <- data.frame(sd, ed)
而且:
myfunction("2016/01/01","2016/01/05", "days")
会产生与此相同的东西:
sd <- c("2016/01/01","2016/01/02","2016/01/03","2016/01/04","2016/01/05")
ed <- c("2016/01/01","2016/01/02","2016/01/03","2016/01/04","2016/01/05")
df <- data.frame(sd, ed)
这是我迄今为止所做的尝试:
range <- function(startdate, enddate, interval){
sd <- seq(as.Date(startdate), as.Date(enddate), interval)
ed <- seq(as.Date(startdate), as.Date(enddate), interval) -1
df <- data.frame(sd,ed)
return(View(df))
}
但是我是否运行了几天或几个月的功能,结束日期是错误的。参见:
range("2016/01/01","2016/01/05","days")
range("2016/01/01","2016/04/30","months")
我如何进行编码,以便我的功能始终如一地返回正确的结束日期,无论我是在查看日期,月份还是数年?我在这里回顾了其他问题,但他们似乎都使用静态区间而不是动态区间。
答案 0 :(得分:1)
library(lubridate)
# Start date and end date should be of character type
# interval should be "day" or "month" or "year"
get_range <- function(startdate, enddate, interval)
{
start <- seq(from = as.Date(start, format = "%m/%d/%Y"),
to = as.Date(end, format = "%m/%d/%Y"),
by = interval)
end <- start + sapply(start, function(x){ifelse(interval == "day", 0,
ifelse(interval == "month",
days_in_month(month(x)) - day(x),
365))})
return(data.frame(start,end))
}