1

我有一个数据框,R其中有一堆列,其中两列表示年份和月份。我想重新格式化这两列,从而形成一个具有不同格式 year_month 的列。当前结构数据框df1为:

... | ... | year | month | ... | ...  
... | ... | 2000 |  P01  | ... | ... 
... | ... | 2000 |  P02  | ... | ... 
... | ... | 2000 |  P03  | ... | ...  
... | ... | 2000 |  P04  | ... | ... 
... | ... | 2000 |  P05  | ... | ... 
 .  |  .  |  .   |  .    |  .  |  .
 .  |  .  |  .   |  .    |  .  |  .

可以看出,数据框的月份列P在每个月份编号前都有字母。现在我想删除这个字母P,重新格式化月份编号以表示月份名称而不是数字(如 Jan. 表示 01,Feb 表示 02),然后将其与 year 列连接,以形成包含月份和年份数据的单列. 因此我想要这样的东西:

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

如何重新格式化两列并将它们合并为一列?

4

1 回答 1

1

as.yearmon与“动物园”一起使用format

通过示例将评论转移到答案:

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
于 2014-09-14T14:56:54.703 回答