Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R how to convert column names into a better Year and Month format

Tags:

date

r

lubridate

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')
like image 733
Sam Avatar asked Nov 07 '25 06:11

Sam


2 Answers

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
like image 146
ThomasIsCoding Avatar answered Nov 09 '25 02:11

ThomasIsCoding


I assume from your tags that this is for a table you are going to present in a web page. I hope so because working with names like this in R is not ideal. In any case, you can convert the names to a date and then format them as desired:

names_to_exclude  <- c("ID", "names")
names_to_change <- names(df)[!names(df) %in% names_to_exclude]
new_names  <- format(
    as.Date(sprintf("%s01", names_to_change), format = "%Y%m%d"),
    "%b %Y"
)

setNames(df, c(names_to_exclude, new_names))
#   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
like image 31
SamR Avatar answered Nov 09 '25 00:11

SamR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!