首页 > 解决方案 > readxl() converts dates to a number

问题描述

I have an xlsx file like this, with date in the first row:

jan/20 mar/2020 jun/2020
A K L
C Y B

For some reason, when importing to R using readxl() function, the dates in the header are converted to a number, like: 15890, 17890, etc.

I know that isn't good practice keeping dates as variables, but even transposing the table the problem remains. I appreciate if someone can help :)

标签: rdatereadxl

解决方案


我不确定您是如何读取/写入数据的,但如果我使用此数据,我将无法重现:

df <- structure(list(`jan/20` = c("A", "C"), `mar/2020` = c("K", "Y"),
`jun/2020` = c("L", "B")), class = "data.frame", row.names = c(NA, -2L))
df

#  jan/20 mar/2020 jun/2020
#1      A        K        L
#2      C        Y        B

#Write the data
writexl::write_xlsx(df, 'test.xlsx')
#Read the data
readxl::read_excel('test.xlsx')

# A tibble: 2 x 3                                                 
# `jan/20` `mar/2020` `jun/2020`
#  <chr>    <chr>      <chr>     
#1 A        K          L         
#2 C        Y          B          

您可以将数字日期更改为您选择的格式:

names(df) <- format(as.Date(as.numeric(names(df)), 
                    origin = '1970-01-01'), '%b/%Y')
df

推荐阅读