'In R, how to mordify 'User-defined function' for date parse
In R, how to mordify below 'User-defined function' my_date_parse?
In below function,I want to replace character GMT+9 and GMT-8 in the beginner,then parse it, but failed.
library(lubridate)
library(tidyverse)
# raw data
df <- data.frame(
date=c("1 Feb 2022 11:48:42 pm GMT+9","1 Feb 2022 9:41:56 am GMT-8","Feb 1, 2022 6:19:26 a.m. PST","Feb 1, 2022 1:22:37 a.m. PST","Feb 12, 2022 7:54:32 a.m. PST","31.01.2022 23:11:54 UTC","Feb 1, 2022 12:00:47 AM PST","Feb 1, 2022 12:44:28 PM PST","Feb 1, 2022 12:20:22 AM PST"),
country=c("AU","AU","CA","CA","CA","DE","US","US","US"))
# User-defined function
my_date_parse <- function(country,date){
# date <- str_replace_all(date,'([GMT+9])',"")
# date <- str_replace_all(date,'([GMT-8])',"")
case_when(
country=='US'~ mdy_hms(date),
country=='DE'~ dmy_hms(date),
country=='CA'~ mdy_hms(date),
country=='AU'~ dmy_hms(date),
)
}
# parse the date with User-defined function
df %>% mutate(date_parsed=my_date_parse(country,date))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
