如何在R中组合年和季度

时间:2019-12-18 19:51:12

标签: r

我正尝试将Year和Quarter组合为新变量“ XQ_4m_bb中的数据YQ,如下所示。但是新变量的输出仍然是NA?这是什么问题?

library(zoo)
X02_4m_bb$YQ <- NA
for(i in 1: nrow(X02_4m_bb)){
  X02_4m_bb$YQ[i] <- as.yearqtr(paste(X02_4m_bb$Year[i], X02_4m_bb$Quarter[i]), format = "%Y-%q")
}

 Year Quarter Revenue   CGS Gross_Profit_M Disp_Income_B    YQ
  <dbl>   <dbl>   <dbl> <dbl>          <dbl>         <dbl> <dbl>
1  1995       1   1275. 1080.           195.        16351.    NA
2  1995       2   1438. 1228.           210.        16481.    NA
3  1995       3   1929. 1672.           257.        16695.    NA
4  1995       4   2576. 2246.           329.        16865.    NA
5  1996       1   1637. 1387.           250.        17122.    NA
6  1996       2   1779. 1510.           268.        17400.    NA

2 个答案:

答案 0 :(得分:1)

您不需要循环

只要做

X02_4m_bb$YQ <- as.yearqtr(paste0(X02_4m_bb$Year, "-", X02_4m_bb$Quarter))

答案 1 :(得分:0)

也许此代码对您有用

as.yearqtr(format(paste(X02_4m_bb$Year[i], X02_4m_bb$Quarter[i])), "%Y%q")