how to change (20Jul22:11:32:00) and (20Jul22) character to Date format MMDDYYYY

Hi,

I'm using R and trying to convert a datetime field From this format 20Jul22:11:32:00 into 07/20/2022 date format.
I could not find any threads that address this exact problem. I actually tried the code below that worked for just the mentioned date. What I need to do is change the format for all the values in the column "DepartDT" in the "Patient" dataset.
Also, how does this work if the date is in this format "20Jul22:11:32:00"

DepartDT <- as.Date('20JUL21', format = '%d%b%y')
format(DepartDT, '%m/%d/%Y')

Thank you

Lubridate is a wonderful package that makes this a breeze.

If you want to leave the dates in actual date format in R so that you can use date functions on them, just omit the format line(s) in the code below.

require(dplyr)
require(lubridate)


vec1 <- '20Jul22:11:32:00'
vec2 <- '20Jul22'


vec_new1 <- dmy_hms(vec1) %>%  
  format(., '%m/%d/%Y')

vec_new2 <- dmy(vec2) %>% 
  format(., '%m/%d/%Y')

Thank you cmeuli07 for the prompt reply. I'm still learning R so my question is how are these codes applied to the dataset's date values?

You can apply it in base R by assigning the transformed values to the old column. This can be done in one step or separated

data$col <- my_function(data$col)

my_result <- my_function(data$col)
data$col <- my_result

But you can use a package like collapse as well, which has the function fmutate() to add new columns and ftransform() to modify existing ones.

data |>
  ftransform(col = my_function(col))

Kind regards

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.