使用read_excel函数导入Excel文件:日期列未正确导入

时间:2018-11-09 22:41:19

标签: r tidyverse

我执行了以下代码以在Rstudio中导入excel文件:

(nms <- names(read_excel("myexcelfile.xlsx")))
(ct <- ifelse(grepl("^Date", nms), "text", "numeric"))
read_excel("myexcelfile.xlsx", col_types = ct)[-c(6:495),-c(3:71)]

结果为以下数据框:

structure(list(Data = c("41731", "41730", "41729", "41726", "41725"
), ABEV3 = c(15.2, 14.9, 15.22, 15.15, 15.18)), row.names = c(NA, 
-5L), class = c("tbl_df", "tbl", "data.frame"))

第一列应为日期(巴西格式:日/月/年)。

enter image description here

我该如何解决?

1 个答案:

答案 0 :(得分:1)

尝试一下:

(nms <- names(read_excel("myexcelfile.xlsx")))
(ct <- ifelse(grepl("^Date", nms), "date", "numeric"))
df <- read_excel("myexcelfile.xlsx", col_types = ct)[-c(6:495),-c(3:71)]

df$Date <- format(as.Date(as.character(df$Date)), "%d-%m-%Y")

与其将其导入为文本,不如将其导入为date,然后按照以下所述的方式对其进行格式化(假设您将Excel保存在df数据框中,并且该列将称为Date,但可以根据需要进行调整。)