将列名读取为日期格式

use*_*640 5 datetime r readxl

我在 Excel 中有如下日期,首先col1是字符,从col2col5是日期格式 (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
Run Code Online (Sandbox Code Playgroud)

我尝试使用readxl库将上述文件导入到 R 中,我的结果显示日期格式的列名在数据集中显示为数字,

如何导入相同格式的Excel日期列?

akr*_*run 6

由于数据集是excel格式,我们可以读取它,read_excel然后将列名更改为原始格式

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')))
Run Code Online (Sandbox Code Playgroud)


zx8*_*754 2

列名不能是日期类。我们可以读取数据,然后从宽格式重新调整为长格式,以便列名称作为日期类位于行中,如下所示:

# 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
Run Code Online (Sandbox Code Playgroud)