尽管是日期格式 lubridate "all formats failed to parse. No formats found" 从 ymd 到 mdy 时出错

despite being in Date format lubridate "all formats failed to parse. No formats found" error when going from ymd to mdy

编辑:已获悉 lubridate 不进行任何转换。

我有一个非常简单的变量,带有 chr 格式的 YMD 日期,但 lubridate::mdy() 拒绝将其转换为 mdy(如果这不是 mdy 应该做的,那么请建议如何使用 lubridate 更改数据排序)。我截断它以摆脱时间,我可以将 as_date 应用于截断版本而不会出错,所以我最终得到六个日期级别:

          .  n   percent
 2020-05-20  6 0.0400000
 2020-05-21 19 0.1266667
 2020-05-25 45 0.3000000
 2020-05-26 47 0.3133333
 2020-05-27 21 0.1400000
 2020-06-04 12 0.0800000

但是任何转换为​​ mdy() after as_date 的尝试都已经使用 lubridate 实现了 Warning message: All formats failed to parse. No formats found. 怎么会这样?我翻阅了之前的 lubridate 个帖子,无法理解为什么简单的格式更改总是失败。

我试过 base 和 tidyverse 版本 test$StartDate2 <- mdy(test$StartDate2) 他们转向 NA

原始数据 test$StartDate: chr [1:150] "2020-05-25 16:11" ... 被截断为 test$StartDate2: chr [1:150] "2020-05-25" "2020-05-27" 然后通过 test$StartDate2 <- as_date(test$StartDate2) 仍然没有被 mdy()

识别
test %>% mutate(StartDate3 = as_date(StartDate2),
+                 StartDate4 = ymd(StartDate2),
+                 StartDate5 = mdy(StartDate2))
# A tibble: 150 x 5
   StartDate        StartDate2 StartDate3 StartDate4 StartDate5
   <chr>            <date>     <date>     <date>     <date>    
 1 2020-05-25 16:11 2020-05-25 2020-05-25 2020-05-25 NA        
 2 2020-05-27 6:55  2020-05-27 2020-05-27 2020-05-27 NA        
 3 2020-05-25 16:41 2020-05-25 2020-05-25 2020-05-25 NA        
 4 2020-05-27 5:58  2020-05-27 2020-05-27 2020-05-27 NA        
 5 2020-05-26 1:28  2020-05-26 2020-05-26 2020-05-26 NA        
 6 2020-05-25 16:51 2020-05-25 2020-05-25 2020-05-25 NA        
 7 2020-05-26 21:11 2020-05-26 2020-05-26 2020-05-26 NA        
 8 2020-05-25 16:08 2020-05-25 2020-05-25 2020-05-25 NA        
 9 2020-05-25 14:38 2020-05-25 2020-05-25 2020-05-25 NA        
10 2020-05-26 21:56 2020-05-26 2020-05-26 2020-05-26 NA     

所有 lubridate 函数(mdyymd 或任何其他)用于将值从字符类型更改为日期类型。日期类型只能以一种形式表示,即YYYY-MM-DD。如果您想要任何其他格式的日期,那么您可能需要具有字符类型的值。要获取其他形式的数据,您可以使用 format(而不是 mdy)。

library(dplyr)
test %>% mutate(StartDate3 = format(StartDate2, '%m-%d-%Y'))

#          StartDate StartDate2 StartDate3
#1  2020-05-25 16:11 2020-05-25 05-25-2020
#2   2020-05-27 6:55 2020-05-27 05-27-2020
#3  2020-05-25 16:41 2020-05-25 05-25-2020
#4   2020-05-27 5:58 2020-05-27 05-27-2020
#5   2020-05-26 1:28 2020-05-26 05-26-2020
#6  2020-05-25 16:51 2020-05-25 05-25-2020
#7  2020-05-26 21:11 2020-05-26 05-26-2020
#8  2020-05-25 16:08 2020-05-25 05-25-2020
#9  2020-05-25 14:38 2020-05-25 05-25-2020
#10 2020-05-26 21:56 2020-05-26 05-26-2020