使用grep用R中的不同值替换每n次和(n&x2B;1)次出现的值

使用grep用R中的不同值替换每n次和(n&x2B;1)次出现的值,r,regex,R,Regex,季度数据 > 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

季度数据

> 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试试看


谢谢。这几乎奏效了。
grep
不会删除字符串末尾的“Q1”。但是使用
year This对我来说是有效的:
year Find and Replace是错误的策略,因为从编程角度来说,这不是您要做的。您没有找到一个特定值并用另一个特定值替换它。您正在用一组具有不同模式的新值替换一组值。
 df.mon$TIME <- rep(df$TIME, each=3)  
  >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
     GEO  month
  3864.6 2000M01
  3864.6 2000M02
  3864.6 2000M03
  3841.3 2000M04
  3841.3 2000M05
  3841.3 2000M06
  3843.0 2000M07
gsub("(?:Q1)", "\\1M01\\2M02\\3M03", df.mon$month)
     2000M01M02M03
     2000M01M02M03
     2000M01M02M03
year <- grep("[0-9]{4}", df.mon$month, value=T)
month <- paste("M", 1:12, sep="")
yearmonth <- paste(year, month, sep="")
df.mon$month <- yearmonth