我使用as.Date(as.yearqtr(test[,1],format ="%qQ%Y"),frac =1)
时遇到问题,但返回错误,并且四分之一年至今未更改。错误是:error in as.yearqtr(as.numeric(x)) (list) object cannot be coerced to type 'double'
这是我在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
更新:实际数据是:
structure(list(...1=c("1Q2019","2Q2019","3Q2019","4Q2019"),...4 = c(0.001, 0.9, 0.873, 0.987)), .Names = c("...1","...4"), row.names = c(NA, -4L), class =c("tbl_df","tbl","data.frame"))
我们可以使用Zoo将其转换为Date并使用frac
获得该季度的最后日期。我们使用一些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
数据:
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))
这里是一个函数,将返回日期向量,给定输入向量的形式为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)
和输出:
>lastDayOfQuarter(dateStrings)
[1] "2019-03-31" "2019-06-30" "2019-09-30" "2019-12-31" "2020-03-31"
>