如何在R中重新格式化数据帧不同列中表示年和月的字符串?

如何在R中重新格式化数据帧不同列中表示年和月的字符串?,r,dataframe,reformat,R,Dataframe,Reformat,我在R中有一个数据框,其中有一串列,其中两列表示年和月周期。我想重新格式化这两列,从而形成一个单独的列,格式为year_month。当前结构数据帧df1是: ... | ... | year | month | ... | ... ... | ... | 2000 | P01 | ... | ... ... | ... | 2000 | P02 | ... | ... ... | ... | 2000 | P03 | ... | ... ... | ... | 2000

我在
R
中有一个数据框,其中有一串列,其中两列表示年和月周期。我想重新格式化这两列,从而形成一个单独的列,格式为year_month。当前结构数据帧df1是:

... | ... | year | month | ... | ...  
... | ... | 2000 |  P01  | ... | ... 
... | ... | 2000 |  P02  | ... | ... 
... | ... | 2000 |  P03  | ... | ...  
... | ... | 2000 |  P04  | ... | ... 
... | ... | 2000 |  P05  | ... | ... 
 .  |  .  |  .   |  .    |  .  |  .
 .  |  .  |  .   |  .    |  .  |  .
可以看出,数据框的月列在每个月号前面有字母
p
。现在我想删除这个字母
P
重新格式化月份编号,以表示月份名称而不是编号(如01为1月,02为2月),然后将其与年份列连接,从而形成一个包含月份和年份数据的列。因此我想要这样的东西:

... | ... | month_year | ... | ...  
... | ... |  Jan. 2000 | ... | ... 
... | ... |  Feb. 2000 | ... | ... 
... | ... |  Mar. 2000 | ... | ...  
... | ... |  Apr. 2000 | ... | ... 
... | ... |  May. 2000 | ... | ... 
 .  |  .  |      .     |  .  |  .
 .  |  .  |      .     |  .  |  .

如何重新格式化这两列并将其合并为一列?

使用“zoo”中的
as.yearmon
以及
格式

用一个例子将评论转换为答案:

df1 <- data.frame(year = 2000, month = c("P01", "P02", "P03", "P04"))
#   year month
# 1 2000   P01
# 2 2000   P02
# 3 2000   P03
# 4 2000   P04

library(zoo)
df2 <- transform(df1, yearmon = as.yearmon(paste0(year, sub("P", "-", month))))
df2$yearmon <- format(df2$yearmon, "%b. %Y")
df2
#   year month   yearmon
# 1 2000   P01 Jan. 2000
# 2 2000   P02 Feb. 2000
# 3 2000   P03 Mar. 2000
# 4 2000   P04 Apr. 2000

df1
library(动物园);transform(df1,yearmon=as.yearmon(paste0(year,sub(“P”),“-”,month))
创建一个数据框,其中包含一个新的列class
“yearmon”
。噢,很常见,我刚想发布这个:)@G.Grothendieck谢谢你的回答。但是我如何在月份名称后面加上一个
,就像2000年1月那样。我试着把它放在
paste0()
中,就像在
paste0(年,分(“P”),“-”,月),“)
中一样,但是什么都没有发生,如果
df2
是上面的数据框,那么
格式(df2$yearmon,%b.%Y”)
@David,如果你发布你的解决方案,我将删除我的评论。