用完整的月份名称替换数据框列名称中的月份名称:

时间:2019-04-30 04:35:09

标签: r rename

我有下面的数据框,其中每月数字都在所示的列中。

Adv_Code    April_OPN   May_OPN June_OPN    July_OPN    Aug_OPN Sep_OPN Oct_OPN Nov_OPN Dec_OPN Jan_OPN Feb_OPN March_OPN
A201        0           0       0           0           0       0       0       0       0       0       0       0
A198        2           0       0           1           2       0       5       0       0       0       0       0
S1212       0           3       4           0           0       3       0       1       0       0       0       0

这些月份中有些是缩写形式,有些是完整的月份名称。 我需要将所有这些都转换为完整的月份名称

Adv_Code    April_OPN   May_OPN June_OPN    July_OPN    August_OPN  September_OPN   October_OPN November_OPN    December_OPN    January_OPN February_OPN    March_OPN
A201        0           0       0           0           0           0               0           0               0               0           0               0
A198        2           0       0           1           2           0               5           0               0               0           0               0
S1212       0           3       4           0           0           3               0           1               0               0           0               0

有人可以帮我吗?

下面是用于再现数据的代码:

Adv_Code <- c('A201','A198','S1212')
April_NOP <- c(0,2,0)
May_NOP <- c(0,0,3)
June_NOP <- c(0,0,4)
July_NOP <- c(0,1,0)
Aug_NOP <- c(0,2,0)
Sep_NOP <- c(0,0,3)
Oct_NOP <- c(0,5,0)
Nov_NOP <- c(0,0,1)
Dec_NOP <- c(0,0,0)
Jan_NOP <- c(0,0,0)
Feb_NOP <- c(0,0,0)
Mar_NOP <- c(0,0,0)

df <- data.frame(Adv_Code,Vintage_Dt,April_NOP,May_NOP,June_NOP,July_NOP,Aug_NOP,Sep_NOP,Oct_NOP,Nov_NOP,Dec_NOP,Jan_NOP,Feb_NOP,Mar_NOP)

1 个答案:

答案 0 :(得分:2)

从列名中提取前3个字符,matchmonth.abb并将其替换为相应的month.name

names(df)[-1] <- paste(month.name[match(substr(names(df)[-1], 1, 3), 
                       month.abb)], "OPN", sep = "_")

df
#  Adv_Code April_OPN May_OPN June_OPN July_OPN August_OPN September_OPN October_OPN November_OPN December_OPN
#1     A201         0       0        0        0          0             0           0            0            0
#2     A198         2       0        0        1          2             0           5            0            0
#3    S1212         0       3        4        0          0             3           0            1            0
#  January_OPN February_OPN March_OPN
#1           0            0         0
#2           0            0         0
#3           0            0         0

FYI,month.abbmonth.name是R中的内置向量

month.abb
# [1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
 month.name
# [1] "January"   "February"  "March"  "April"  "May"  "June"  "July"  
#     "August"  "September" "October"   "November"  "December"