【问题标题】:Is there a way to import dates from an excel file as strings?有没有办法将excel文件中的日期作为字符串导入?
【发布时间】:2020-08-31 21:00:23
【问题描述】:

我正在从事一个项目,该项目涉及使用 R 来清理 excel 文件中的日期条目,以便将它们上传到数据库。在 excel 文件中,一些日期已经采用日期格式(即“8/18/2020”),而另一些则不是(即“8/18/2020 2027”)。我想将日期列导入到 R 中,这样我就可以运行代码来重新格式化类似“8/18/2020 2027”的单元格。我目前正在使用 readxl 库中的 read_excel() 命令导入 excel 文件,使用与此类似的语法:

read_excel("filepath", col_types = c("date"))

我遇到的问题是,如果我将该列定义为日期列,readexcel() 将无法将类似“8/18/2020 2027”的单元格识别为有效日期,并且不会导入这些单元格.

另一方面,如果我将该列定义为文本列,readexcel() 会将类似“8/18/2020”的单元格简化为不同的数字 (44063)。

有没有办法将整行导入到 R 中而其条目不受影响?

【问题讨论】:

  • 您可以将您的 Excel 文件保存为平面文件(例如 .txt、.csv)吗?我认为使用 read.csv 或 read_csv 函数发生这些转换的可能性较小。
  • 从@stefan 的回答开始,考虑一种尝试各种格式的方法,直到所有值都成功转换或没有任何效果...stackoverflow.com/a/60748268/3358272

标签: r excel


【解决方案1】:

使用question 的答案,您可以将该列读取为文本,并将表示日期的数字转换为如下字符:

# Read xl file. Read as text
# foo <- readxl::read_excel("test.xlsx", col_names = "date")

# dput of test.xlsx
foo <- structure(list(date = c("44061", "8/18/2020 2027")), row.names = c(NA, 
                                                                          -2L), class = c("tbl_df", "tbl", "data.frame"))

foo
#>             date
#> 1          44061
#> 2 8/18/2020 2027

foo$date <- ifelse(grepl("^\\d+$", foo$date), format(as.Date(as.numeric(foo$date), origin = "1899-12-30"), "%m/%d/%Y"), foo$date)
#> Warning in as.Date(as.numeric(foo$date), origin = "1899-12-30"): NAs introduced
#> by coercion

foo
#>             date
#> 1     08/18/2020
#> 2 8/18/2020 2027

【讨论】:

    猜你喜欢
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 2020-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    相关资源
    最近更新 更多