简体   繁体   English

将 YEARQT 格式的字符转换为 R 中的季度“日期”

[英]Convert character in format YEARQT to a quarterly "date" in R

Date日期
1960Q1 1960Q1
1960Q2 1960Q2
1960Q3 1960Q3
1960Q4 1960Q4
1961Q1 1961Q1
1961Q2 1961Q2

I have the following data.frame.我有以下数据框。 I am trying to put this first column into a tsibble.我正在尝试将第一列放入一个 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我尝试使用zoo

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. %YQ%q%Y代表年份, Q代表初始格式中的 Q, %q代表季度。

Code代码

library(zoo)

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

Output 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))

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

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