使用as.yearqtr处理字符串 [英] Processing a string using as.yearqtr

查看:30
本文介绍了使用as.yearqtr处理字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

早上好

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

Let's assume I have the following variable in R:

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

要将其转换为yearqtr,我以为这可以解决问题:

To transform this into yearqtr, I would have thought that this would do the trick:

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

但是,我得到的只是:

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

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

What's the best way to fix this? After some experimentation I also noticed:

> 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"

任何想法都会受到赞赏,

Any thoughts would be appreciated,

菲利普

----更新:

> 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

推荐答案

gsub 非常方便,如果您希望进行这样的常规字符串操作:

gsub comes in super handy if you would like to have such a regular string manipulation:

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

这篇关于使用as.yearqtr处理字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆