Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
882 views
in Technique[技术] by (71.8m points)

r - Convert quarter/year format to a date

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"

This the code of my function.

.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)
  }

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...