簡體   English   中英

使用 lubridate 和管道將日期轉換為年月日

[英]convert date to year-month-day using lubridate and pipes

我想使用 lubridate 和管道將“日/月/年”中的日期轉換為“年/月/日”,但我遇到了問題。 此外,“public_release”的第一行已切換日期和月份。 bwg_releasepublic_release的前三行應反映 1 月 6 日的日期。 例如

    datasets %>%
+   select(bwg_release, public_release)
  bwg_release public_release
1  06/01/2016     01/06/2018
2  06/01/2016     06/01/2018
3  06/01/2016     06/01/2018
4  17/04/2016     17/04/2016

當前 output:

datasets %>% 
+   mutate(bwg_release_new_date = format(dmy(bwg_release),"%Y/%m/%d")) %>%
+   mutate(public_release_new_date = format(dmy(public_release),"%Y/%m/%d")) %>%
+   select(bwg_release_new_date,public_release_new_date)
  bwg_release_new_date public_release_new_date
1           2016/01/06              2018/06/01
2           2016/01/06              2018/01/06
3           2016/01/06              2018/01/06
4           2016/04/17              2016/04/17     

所需的 output:

bwg_release_new_date public_release_new_date
1           2016/01/06              2018/01/06
2           2016/01/06              2018/01/06
3           2016/01/06              2018/01/06
4           2016/04/17              2016/04/17

我相信建議是使用基本format function。 只需使用dmy()讀取日期,然后定義您的格式。

library(dplyr)
library(lubridate)
datasets %>% 
  mutate(output = format(dmy(bwg_release), format = "%Y/%m/%d"))
  bwg_release     output
1  06/01/2016 2016/01/06
2  06/01/2016 2016/01/06
3  06/01/2016 2016/01/06
4  17/04/2016 2016/04/17

為了完整起見使用正則表達式雖然@IanCampbell(+1)解決方案是go的方式。

datasets %>%
 mutate(bwg_release=ymd(gsub("(\\d+)/(\\d+)/(\\d+)","\\3/\\2/\\1",  bwg_release)))
# A tibble: 4 x 1
  bwg_release
  <date>     
1 2016-01-06 
2 2016-01-06 
3 2016-01-06 
4 2016-04-17 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM