将季度年度转换为 R 中季度的最后日期 [英] convert quarter year to last date of quarter in R
本文介绍了将季度年度转换为 R 中季度的最后日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在使用 as.Date(as.yearqtr(test[,1],format ="%qQ%Y"),frac =1)
时遇到问题,但它返回一个错误,而 quater-year 至今没有改变.错误是:as.yearqtr(as.numeric(x)) (list) 对象中的错误不能被强制输入'double'
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. The error is:
error in as.yearqtr(as.numeric(x)) (list) object cannot be coerced to type 'double'
这是我在 R 中的数据框.
This is my dataframe in R.
TIME VALUE
1Q2019 1
2Q2019 2
3Q2019 3
4Q2019 4
理想的输出是
TIME VALUE
2019-03-31 1
2019-06-30 2
2019-09-30 3
2019-12-31 4
推荐答案
我们可以用zoo转换成Date,用frac
得到季度的最后日期.我们使用一些 RegEx 重新排列为 zoo
的合适格式:
We can convert to Date with zoo and get the last date of the quarter with frac
. We use some RegEx to rearrange in zoo
's suitable format:
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
数据:
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))
这篇关于将季度年度转换为 R 中季度的最后日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文