I have a dataframe which has year and month as column names for some cloumns.
ID <- c(1, 3, 9L, 21L, 15L)
names <- c("as", "ds", "sds", "www", "jgh")
`201401` <- c("12L", "310L", "2379L", "234L", "14L")
`201402` <- c("12L", "310L", "2379L", "234L", "14L")
`201403` <- c("12L", "310L", "2379L", "234L", "14L")
`201404` <- c("12L", "310L", "2379L", "234L", "14L")
I would like to conver year month cloumns names into date format so that columns such as 201401
becomes Jan 2014
and so on.
df <- data.frame(ID, names, `201401`, `201402`, `201403`, `201404`, check.names = FALSE)
betterDate <- as.Date(df$201401,"%m/%y") #possible solution ?
What be the best approach to have the following outcome ?
Expected Outcome df Column names as:
ID =c(1, 3, 9L, 21L, 15L)
names = c("as","ds" ,"sds" ,"www", "jgh")
Jan 2014 = c('12L', '310L','2379L', '234L', '14L')
Feb 2014 =c('12L', '310L','2379L', '234L', '14L')
Mar 2014 =c('12L', '310L','2379L', '234L', '14L')
April 2014 =c('12L', '310L','2379L', '234L', '14L')
You can use ym
+ format
library(lubridate)
names(df)[-(1:2)] <- format(ym(names(df[-(1:2)])), "%b %Y")
and you will obtain
> df
ID names Jan 2014 Feb 2014 Mar 2014 Apr 2014
1 1 as 12L 12L 12L 12L
2 3 ds 310L 310L 310L 310L
3 9 sds 2379L 2379L 2379L 2379L
4 21 www 234L 234L 234L 234L
5 15 jgh 14L 14L 14L 14L