简体   繁体   中英

Convert character in format YEARQT to a quarterly "date" in R

Date
1960Q1
1960Q2
1960Q3
1960Q4
1961Q1
1961Q2

I have the following data.frame. I am trying to put this first column into a tsibble. Now I have a problem. How can I switch to a date so that it can be read as a quarter.

I tried zoo using

DATA.QTR <- DATA.QTR %>%   mutate(QUARTER = as.Date(as.yearqtr(Date, "%Y %Q")))

but it's not reading it.

You almost got it. The format needs to be sligthly adapted.

%YQ%q : %Y stands for the year, Q stands for the Q in your inital format and %q stands for the quarter.

Code

library(zoo)

DATA.QTR <- DATA.QTR %>% mutate(QUARTER = as.Date(as.yearqtr(format(Date), "%YQ%q")))

Output

> DATA.QTR
# A tibble: 6 x 2
  Date   QUARTER   
  <chr>  <date>    
1 1960Q1 1960-01-01
2 1960Q2 1960-04-01
3 1960Q3 1960-07-01
4 1960Q4 1960-10-01
5 1961Q1 1961-01-01
6 1961Q2 1961-04-01

Data

DATA.QTR <- structure(list(Date = c("1960Q1", "1960Q2", "1960Q3", "1960Q4", 
                                    "1961Q1", "1961Q2")), class = c("tbl_df", "tbl", "data.frame"
                                    ), row.names = c(NA, -6L))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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