Converting numbers into Dates

Hi All,

This is my first here on the forum basically I am really embarrass to ask this question as it should be very easy but I cannot find anything relating to it on the internet.

Attach picture show an excel file which I have imported to R Studio and it had column names which was actually dates on excel but upon importing it on R Studio the dates changed to numbers which R is considering as character as they are column names, Can anyone help changing these numbers back to dates.

Now I know to change the number its a pretty simple code: as.Date(x,origin=189....)

but I want to apply it on column names which I found so far pretty hard thing to do.

Please any help will be appreciated.

This solution is sort of ugly but it does what you want.

library(tidyverse)

df <- tribble(~ "43831", ~ "43832",
              "A", "A",
              "A", "A",
              "A", "A")

names(df) <- map_chr(names(df), ~ as.character(as.Date(as.numeric(.), 
                                                       origin = "1899-12-30")))

print(df)
#> # A tibble: 3 x 2
#>   `2020-01-01` `2020-01-02`
#>   <chr>        <chr>       
#> 1 A            A           
#> 2 A            A           
#> 3 A            A

Created on 2020-05-15 by the reprex package (v0.3.0)

I think you can avoid map and do this directly with:

names(df) = as.Date(as.numeric(names(df)), origin="1899-12-30")
2 Likes

You're right. I don't know why I thought map() was needed. That's what I get for solving puzzles at 1 AM. :sweat_smile:

1 Like

Thank you so much Joels, it works perfectly much appreciated your help.

Thank you siddharthparhbu your code works too.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.