Reputation: 21
How do you convert a string like "Q12000" into quarter format using as.yearqtr
in R?
I have a vector of quarters:
x <- c("Q12000", "Q22000", "Q32000")
I tried the following code:
library(zoo)
as.yearqtr(x, format = "Q%q%Y")
# [1] NA NA NA
The result should be "2000 Q1" "2000 Q2" "2000 Q3". Instead, I get all NA
.
Upvotes: 2
Views: 614
Reputation: 269852
Unfortunately the implementation does not understand that a quarter can be only one digit so it needs to be delimited by a non-digit. For example, insert a space after the quarter:
as.yearqtr(sub("(..)", "\\1 ", x), format = "Q%q %Y")
## [1] "2000 Q1" "2000 Q2" "2000 Q3"
or put it into default format first:
as.yearqtr(sub("Q(.)(....)", "\\2-\\1", x))
## [1] "2000 Q1" "2000 Q2" "2000 Q3"
Note:
x <- c("Q12000", "Q22000", "Q32000")
Upvotes: 2