问题描述
我创建了一个将四分之一年格式的矢量强制转换为日期矢量的函数。
I created a function that coerce a vector of quarters-years format to a vector of dates.
.quarter_to_date(c("Q1/13","Q2/14"))
[1] "2013-03-01" "2014-06-01"
这是我函数的代码。
.quarter_to_date <-
function(x){
ll <- strsplit(gsub('Q([0-9])[/]([0-9]+)','\\1,\\2',x),',')
res <- lapply(ll,function(x){
m <- as.numeric(x[1])*3
m <- ifelse(nchar(m)==1,paste0('0',m),as.character(m))
as.Date(paste(x[2],m,'01',sep='-'),format='%y-%m-%d')
})
do.call(c,res)
}
我的函数工作正常,但看起来又长又有点复杂。我认为应该在其他软件包中完成此操作(例如 lubridate
),但是我找不到它。有人可以帮我简化这段代码吗?
My function works fine but it looks long and a little bit complicated. I think that this should be already done in other packages( lubridate
for example) But I can't find it. Can someone help me to simplify this code please?
推荐答案
1)动物园程序包中有一个 yearqtr
类。转换为该值,然后转换为日期
类:
1) The zoo package has a "yearqtr"
class. Convert to that and then to "Date"
class:
library(zoo)
x <- c("Q1/13","Q2/14")
as.Date(as.yearqtr(x, format = "Q%q/%y"))
## [1] "2013-01-01" "2014-04-01"
2)这也可以获取月份的最后一天而不是第一天:
2) This also works to get the last day of the month instead of the first:
as.Date(as.yearqtr(x, format = "Q%q/%y"), frac = 1)
## [1] "2013-03-31" "2014-06-30"
3)也请考虑不要转换为日期
类,而直接使用 yearqtr
类:
3) Also consider not converting to "Date"
class at all and just using "yearqtr"
class directly:
as.yearqtr(x, format = "Q%q/%y")
## [1] "2013 Q1" "2014 Q2"
这篇关于将季度/年格式转换为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!