简体   繁体   English

将季度年转换为 R 中季度的最后日期

[英]convert quarter year to last date of quarter in R

I have an issue when I use as.Date(as.yearqtr(test[,1],format ="%qQ%Y"),frac =1) , but it returns an error,and quater-year didn't change to date.我在使用as.Date(as.yearqtr(test[,1],format ="%qQ%Y"),frac =1)时遇到问题,但它返回错误,并且季度没有改变迄今为止。 The error is: error in as.yearqtr(as.numeric(x)) (list) object cannot be coerced to type 'double'错误是: error in as.yearqtr(as.numeric(x)) (list) object cannot be coerced to type 'double'

This is my dataframe in R.这是我在 R 中的 dataframe。

 TIME VALUE 1Q2019 1 2Q2019 2 3Q2019 3 4Q2019 4

The ideal output is理想的 output 是

 TIME VALUE 2019-03-31 1 2019-06-30 2 2019-09-30 3 2019-12-31 4

We can convert to Date with zoo and get the last date of the quarter with frac .我们可以使用 zoo 转换为 Date 并使用frac获取该季度的最后日期。 We use some RegEx to rearrange in zoo 's suitable format:我们使用一些 RegEx 以zoo的合适格式重新排列:

df$TIME=as.Date(as.yearqtr(gsub("(\\d)(Q)(\\d{1,})","\\3 Q\\1",df$TIME)),frac = 1)
 df
        TIME VALUE
1 2019-03-31     1
2 2019-06-30     2
3 2019-09-30     3
4 2019-12-31     4

Data:数据:

df <-structure(list(TIME = structure(1:4, .Label = c("1Q2019", "2Q2019", 
"3Q2019", "4Q2019"), class = "factor"), VALUE = 1:4), class = "data.frame", row.names = c(NA, 
-4L))

Here is a function that will return a vector of dates, given an input vector in the form of 1Q2019...这是一个 function,它将返回一个日期向量,给定 1Q2019 形式的输入向量...

dateStrings <- c("1Q2019","2Q2019","3Q2019","4Q2019","1Q2020")

lastDayOfQuarter <- function(x){
     require(lubridate)
     result <- NULL
     months <-c(3,6,9,12)
     days <- c(31,30,30,31)

     for(i in 1:length(x)) {
          qtr <- as.numeric(substr(x[i],1,1))
          result[i] <- mdy(paste(months[qtr],days[qtr],(substr(x[i],3,6)),sep="-")) 
     }
     as.Date(result)

}
lastDayOfQuarter(dateStrings)

and the output:和 output:

>lastDayOfQuarter(dateStrings)
[1] "2019-03-31" "2019-06-30" "2019-09-30" "2019-12-31" "2020-03-31"
> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM