使用as.yearqtr处理字符串

时间:2014-04-09 14:08:59

标签: r date

早上好,

我们假设我在R中有以下变量:

r <- c("Q412", "Q113", "Q213","Q313")

要将此转换为yearqtr,我会认为这样可以解决问题:

as.yearqtr(r, format = "Q%q%y")

但是,我得到的只是:

"NA QNA" "NA QNA" "NA QNA" "NA QNA"

解决此问题的最佳方法是什么?经过一些实验,我也注意到了:

> as.yearqtr(x = "14 Q2", format = "%y Q%q")
[1] "2014 Q2"
> as.yearqtr(x = "14Q2", format = "%yQ%q")
[1] "2014 Q2"
> as.yearqtr(x = "Q2 14", format = "Q%q %y")
[1] "2014 Q2"
> as.yearqtr(x = "Q214", format = "Q%q%y")
[1] "NA QNA"

任何想法都会受到赞赏,

菲利普

----更新:

> sessionInfo()

R version 3.0.3 (2014-03-06)
Platform: i386-w64-mingw32/i386 (32-bit)

locale:
[1] LC_COLLATE=English_United States.1252 
[2] LC_CTYPE=English_United States.1252   
[3] LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C                          
[5] LC_TIME=English_United States.1252    

attached base packages:
[1] grid      stats     graphics  grDevices utils     datasets  methods  
[8] base     

other attached packages:
 [1] gridExtra_0.9.1  ggplot2_0.9.3.1  lattice_0.20-27  xts_0.9-7       
 [5] Haver_1.2        forecast_5.2     timeDate_3010.98 dyn_0.2-9       
 [9] lubridate_1.3.3  markdown_0.6.4   gplots_2.12.1    reshape_0.8.4   
[13] plyr_1.8.1       googleVis_0.4.7  zoo_1.7-11       shiny_0.9.1     

loaded via a namespace (and not attached):
 [1] bitops_1.0-6              caTools_1.16             
 [3] colorspace_1.2-4          dichromat_2.0-0          
 [5] digest_0.6.4              fracdiff_1.4-2           
 [7] gdata_2.13.2              gtable_0.1.2             
 [9] gtools_3.3.1              httpuv_1.2.3             
[11] KernSmooth_2.23-10        labeling_0.2             
[13] MASS_7.3-29               memoise_0.1              
[15] munsell_0.4.2             nnet_7.3-7               
[17] parallel_3.0.3            proto_0.3-10             
[19] quadprog_1.5-5            RColorBrewer_1.0-5       
[21] Rcpp_0.11.1               RcppArmadillo_0.4.100.2.1
[23] reshape2_1.2.2            RJSONIO_1.0-3            
[25] scales_0.2.3              stringr_0.6.2            
[27] tools_3.0.3               tseries_0.10-32          
[29] xtable_1.7-3

2 个答案:

答案 0 :(得分:1)

确定,

如果有其他人遇到此问题,请点击以下一行:

Date.Fix <- as.yearqtr(paste(substr(r,1,2), " 20", substr(r, 3,4), sep=""), format = "Q%q %Y")

答案 1 :(得分:1)

如果您希望进行这样的常规字符串操作,

gsub会非常方便:

library('zoo')
r <- c("Q412", "Q113", "Q213","Q313")
as.yearqtr(
  gsub('(Q.)(.*)', '\\1-\\2', r), # Place a hyphen between the Q(char), & the rest of the string
  format='Q%q-%y')