【发布时间】:2015-06-23 02:27:16
【问题描述】:
季度数据
> df
TIME GEO Value
2000Q1 Austria 3864.6
2000Q2 Austria 3841.3
2000Q3 Austria 3843.0
2000Q4 Austria 3847.2
2001Q1 Austria 3853.5
2001Q2 Austria 3875.2
2001Q3 Austria 3886.7
2001Q4 Austria 3921.9
2002Q1 Austria 3865.2
2002Q2 Austria 3872.4
2002Q3 Austria 3876.0
2002Q4 Austria 3887.9
2003Q1 Austria 3938.3
2003Q2 Austria 3954.5
2003Q3 Austria 3972.8
2003Q4 Austria 3971.9
我天真地将季度数据转换为月度数据
df.mon <- rep(df$Value, each=3)。我为df$TIME 做同样的事情
df.mon$TIME <- rep(df$TIME, each=3)
我想将这些时间标识符转换为月度标识符,以便我可以轻松地使用 df.mon 作为月度数据的权重。
所以,我有
>head(df.mon, n=10)
GEO month
3864.6 2000Q1
3864.6 2000Q1
3864.6 2000Q1
3841.3 2000Q2
3841.3 2000Q2
3841.3 2000Q2
3843.0 2000Q3
3843.0 2000Q3
3843.0 2000Q3
3847.2 2000Q4
我想用M01替换Q1的第1、4、7等出现,Q1的第2、5、8等出现用M02等等,以产生:
GEO month
3864.6 2000M01
3864.6 2000M02
3864.6 2000M03
3841.3 2000M04
3841.3 2000M05
3841.3 2000M06
3843.0 2000M07
与此最接近的解释是here,似乎使用grep 和反向引用\1 是可行的方法(一个有用的列表是here)。
我试过了,
gsub("(?:Q1)", "\\1M01\\2M02\\3M03", df.mon$month)
这只会给我
2000M01M02M03
2000M01M02M03
2000M01M02M03
我尝试过其他规范,例如 gsub("(?:Q1)(?:Q1)(?:Q1)", "\\1M01\\2M02\\3M03", df.mon$month),但没有进行任何替换。
我真的不明白(?: ) 命令发生了什么(而且似乎没有必要),而且我不知道 Perl,所以我不知道如何使这个看似简单的替换工作。
【问题讨论】: