-4

I have a DS which consists of numbers as a columns name , how to convert them as dates as below.

I/P:
Name    41275   41306   41334   41365   ..  41395
NY       20       33     55      24     ..   656
CA       943     348     44      45     ..   549

O/P:
Name    1/1/2013 2/1/2013 3/1/2013  4/1/2013 .. 5/1/2013
NY        20       33      55        24     ..   656
CA        943     348      44        45     ..   549

Thanks in advance

neilfws
  • 32,751
  • 5
  • 50
  • 63
user5860640
  • 71
  • 2
  • 7
  • How did you do that? R really doesn't like data.frames with numbers or dates for column names. Everything will be coerced to character. Is this just for display purposes? – MrFlick Apr 11 '17 at 05:36
  • What do the numbers represent? Days since...? That is your origin. – neilfws Apr 11 '17 at 05:37
  • 1
    Naming your columns in such a way is considered bad practise. It is better to [convert your data to long format](http://stackoverflow.com/q/2185252/2204410) and keep the dates as a column. – Jaap Apr 11 '17 at 06:50

1 Answers1

2

We can use as.Date with origin

names(df1)[-1] <-  format(as.Date(as.numeric(names(df1)[-1]),
                                       origin = "1899-12-30"), "%m/%d/%Y")

data

df1 <- structure(list(Name = structure(c(2L, 1L), .Label = c("CA", "NY"
), class = "factor"), `41275` = c(20L, 943L), `41306` = c(33L, 
348L), `41334` = c(55L, 44L), `41365` = c(24L, 45L), `41395` = c(656L, 
549L)), .Names = c("Name", "41275", "41306", "41334", "41365", 
"41395"), class = "data.frame", row.names = c(NA, -2L))
akrun
  • 874,273
  • 37
  • 540
  • 662