Reputation: 169
I want to turn a date in "day/month/year" to "year/month/day" using lubridate and pipes but I'm having problems. Also, the first row of 'public_release' has day and month switched. The first three rows of both bwg_release
and public_release
should reflect a January 6 date.
E.g.
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:
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:
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
Upvotes: 1
Views: 1084
Reputation: 3888
For the sake of completeness Using regular expression although @IanCampbell (+1) solution is the way to 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
Upvotes: 1
Reputation: 24888
I believe the recommendation is to use the base format
function. Just read the date with dmy()
and then define your format.
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
Upvotes: 2