将季度/年份格式转换为日期

22

我创建了一个函数,可以将季度-年格式的向量强制转换为日期向量。

.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)应该已经完成了这个功能。但我找不到它。请问是否有人能帮我简化这段代码呢?

2个回答

38

1) zoo包含一个名为"yearqtr"的类。将其转换为该类,然后再转换为"Date"类:

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) 如果需要获取当前季度的最后一天,可以使用以下方式:

as.Date(as.yearqtr(x, format = "Q%q/%y"), frac = 1)
## [1] "2013-03-31" "2014-06-30"

3) 考虑不要将数据类型转换为"Date"类,而是直接使用"yearqtr"类:

as.yearqtr(x, format = "Q%q/%y")
## [1] "2013 Q1" "2014 Q2"

0

我之前也遇到类似的问题,但是我想避免增加依赖,所以我使用了这个函数。

q_to_date = function(text_value){
  # separate the quarter and year values
  quarter <- gsub(strsplit(text_value, "/")[[1]][1],pattern = "Q",replacement = "")
  year_suffix <- strsplit(text_value, "/")[[1]][2]
  
  # convert the year suffix to a full year
  year <- as.numeric(paste0("20", year_suffix))
  
  # create a date object for the first day of the quarter
  date <- as.Date(paste0(year, "-", ((as.numeric(quarter) - 1) * 3 + 1), "-01"))
  
  return(date)
}

> q_to_date(text_value = "Q1/13")
[1] "2013-01-01"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接