5

I have date in Excel as follows, first col1 as char and from col2 to col5 is in date format (mm/dd/yyyy)

id   1/1/2016   2/1/2016  3/1/2016  4/1/2016  5/1/2016
1     23         545       33         55          66
2     454        536       66         80          11
3     83         585        9         10          19

I tried to import the above file in to R using readxl library, and my result shows column names which are in date format shows as number in dataset,

How to import Excel date column with same format?

zx8754
  • 52,746
  • 12
  • 114
  • 209
user5860640
  • 71
  • 2
  • 7

2 Answers2

7

As the dataset is in excel format, we can read it with read_excel and then change the column names to its original format

library(readxl)
library(dplyr)
read_excel("yourdata.xlsx" %>% 
    setNames(., c('id', format(as.Date(as.numeric(names(.)[-1]), 
                   origin = '1899-12-30'), '%m/%d/%Y')))
akrun
  • 874,273
  • 37
  • 540
  • 662
2

Column names cannot be date class. We could read the data then reshape from wide to long format, so that column names are in rows as date class, see below:

# Save Excel sheet as CSV, then read the data with the headers and without checking the names for columns.
df1 <- read.table(text="id   1/1/2016   2/1/2016  3/1/2016  4/1/2016  5/1/2016
1     23         545       33         55          66
2     454        536       66         80          11
3     83         585        9         10          19",
                  header = TRUE, check.names = FALSE)


library(dplyr)
library(tidyr)

df1 %>%
  gather(myDate, value, -id) %>% 
  mutate(myDate = as.Date(myDate, format = "%d/%m/%Y"))

#    id     myDate value
# 1   1 2016-01-01    23
# 2   2 2016-01-01   454
# 3   3 2016-01-01    83
# 4   1 2016-01-02   545
# 5   2 2016-01-02   536
# 6   3 2016-01-02   585
# 7   1 2016-01-03    33
# 8   2 2016-01-03    66
# 9   3 2016-01-03     9
# 10  1 2016-01-04    55
# 11  2 2016-01-04    80
# 12  3 2016-01-04    10
# 13  1 2016-01-05    66
# 14  2 2016-01-05    11
# 15  3 2016-01-05    19
zx8754
  • 52,746
  • 12
  • 114
  • 209