如何在 R 中将 1 到 12 之间的数字转换为缩写月份?
有时月份的日期矢量会以数字形式记录,此时将其视为日期矢量进行处理或可视化会变得比较困难。例如,如果一个月份的矢量中有表示 1 月的数字 1、表示 2 月的数字 2,如此等等,那么该矢量将被视为一个数字矢量,而不是表示月份的矢量。为了将这种类型的矢量转换为缩写月份,如 Jan、Feb 等,我们可以使用 month.abb 函数。
示例
Month1<-c(1,8,5,7,2) month.abb[Month1] [1] "Jan" "Aug" "May" "Jul" "Feb" Month2<-c(1,2,3,4,5,6) month.abb[Month2] [1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" Month3<-c(1,3,5,7,9,11) month.abb[Month3] [1] "Jan" "Mar" "May" "Jul" "Sep" "Nov" Month4<-c(2,4,8,10) month.abb[Month4] [1] "Feb" "Apr" "Aug" "Oct" Month4<-c(5,7,4,5,2,7,4,1) Month45<-c(5,7,4,5,2,7,4,1) Month5<-c(5,7,4,5,2,7,4,1) month.abb[Month5] [1] "May" "Jul" "Apr" "May" "Feb" "Jul" "Apr" "Jan" Month6<-rep(c(1:12),times=10) Month6 [1] 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12 1 [26] 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12 1 2 [51] 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 [76] 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 [101] 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12 month.abb[Month6] [1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" [13] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" [25] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" [37] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" [49] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" [61] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" [73] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" [85] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" [97] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" [109] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" Month7<-sample(1:12,50,replace=TRUE) Month7 [1] 11 9 12 8 6 2 7 12 1 12 7 2 2 2 8 8 6 4 1 7 1 3 1 4 4 [26] 12 2 12 8 4 10 2 10 12 10 7 3 11 12 2 10 6 9 3 6 8 5 4 2 7 month.abb[Month7] [1] "Nov" "Sep" "Dec" "Aug" "Jun" "Feb" "Jul" "Dec" "Jan" "Dec" "Jul" "Feb" [13] "Feb" "Feb" "Aug" "Aug" "Jun" "Apr" "Jan" "Jul" "Jan" "Mar" "Jan" "Apr" [25] "Apr" "Dec" "Feb" "Dec" "Aug" "Apr" "Oct" "Feb" "Oct" "Dec" "Oct" "Jul" [37] "Mar" "Nov" "Dec" "Feb" "Oct" "Jun" "Sep" "Mar" "Jun" "Aug" "May" "Apr" [49] "Feb" "Jul" month.abb[Month8] [1] "Feb" "Feb" "Apr" "Jan" "Feb" "May" "Apr" "Jun" "May" "Feb" "May" "Jan" [13] "Apr" "Feb" "May" "May" "Apr" "May" "Jan" "May" "Mar" "Feb" "Feb" "Jun" [25] "Feb" "Feb" "May" "Mar" "Feb" "Jan" "May" "May" "Apr" "Jan" "Jun" "May" [37] "May" "Jun" "Jan" "Jun" "Apr" "May" "Feb" "Jun" "Feb" "Mar" "Apr" "Feb" [49] "Jan" "Jan"
广告