[英]convert date to year-month-day using lubridate and pipes
I want to turn a date in "day/month/year" to "year/month/day" using lubridate and pipes but I'm having problems.我想使用 lubridate 和管道将“日/月/年”中的日期转换为“年/月/日”,但我遇到了问题。 Also, the first row of 'public_release' has day and month switched.
此外,“public_release”的第一行已切换日期和月份。 The first three rows of both
bwg_release
and public_release
should reflect a January 6 date. bwg_release
和public_release
的前三行应反映 1 月 6 日的日期。 Eg例如
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
Current output:当前 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
Desired output:所需的 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
I believe the recommendation is to use the base format
function.我相信建议是使用基本
format
function。 Just read the date with dmy()
and then define your format.只需使用
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
For the sake of completeness Using regular expression although @IanCampbell (+1) solution is the way to go.为了完整起见使用正则表达式虽然@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.