I have the following dates:
my_dataset <- tibble(my_date = c("03-05-2020", "04-05-2020", "05-05-2020", "06-05-2020"))
I would like to create a new column called nice_dates
which has the date format as: dd/mm/yyyy format, so I would end up with something like this:
my_date | nice_dates
03-05-2020 | 03/05/2020
04-05-2020 | 04/05/2020
05-05-2020 | 05/05/2020
06-05-2020 | 06/05/2020
I have tried using the lubridate pacakge but get stuck when defining the new format i know it should be "%d/%m/%Y" however using as.Date() yields NA.
Should i just use gsub instead?
@ThoVu is almost there. So for completeness, a much simpler answer with only base R.
Code## input data as before df <- data.frame(my_date = c("03-05-2020", "04-05-2020", "05-05-2020", "06-05-2020")) ## create Date objects using base R df$parsed <- strptime(df$my_date, "%d-%m-%Y") ## format them to spec df$nice_dates <- format(df$parsed, "%d/%m/%Y")
Output
R> df <- data.frame(my_date = c("03-05-2020", "04-05-2020", "05-05-2020", "06-05-2020")) R> df$parsed <- strptime(df$my_date, "%d-%m-%Y") R> df$nice_dates <- format(df$parsed, "%d/%m/%Y") R> df my_date parsed nice_dates 1 03-05-2020 2020-05-03 03/05/2020 2 04-05-2020 2020-05-04 04/05/2020 3 05-05-2020 2020-05-05 05/05/2020 4 06-05-2020 2020-05-06 06/05/2020 R>
My general recommendation is to never ever use string manipulations or regular expressions on date inputs when you could use proper date parsers.
You need to first convert dates to date class and then use format
to get data in the format you want. Since the final output that you want is character you can also use gsub
here.
library(dplyr)
my_dataset %>%
mutate(nice_dates = format(as.Date(my_date, '%d-%m-%Y'), '%d/%m/%Y'),
nice_dates_gsub = gsub('-', '/', my_date))
# A tibble: 4 x 3
# my_date nice_dates nice_dates_gsub
# <chr> <chr> <chr>
#1 03-05-2020 03/05/2020 03/05/2020
#2 04-05-2020 04/05/2020 04/05/2020
#3 05-05-2020 05/05/2020 05/05/2020
#4 06-05-2020 06/05/2020 06/05/2020
You can also use lubridate::dmy(my_date)
to convert data to date class.
Here you can use anytime
package to convert to date format then replace - with slash /
library(dplyr)
library(stringr)
library(anytime)
my_dataset <- tibble(my_date = c("03-05-2020", "04-05-2020", "05-05-2020", "06-05-2020"))
my_dataset$mice_date <- format(anydate(my_dataset$my_date), '%m/%d/%Y')
# my_date mice_date
# <chr> <chr>
# 1 03-05-2020 03/05/2020
# 2 04-05-2020 04/05/2020
# 3 05-05-2020 05/05/2020
# 4 06-05-2020 06/05/2020
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.