Creating a date from a string inside a data frame

Viewed 26

Having a data frame:

x <- c('zondag 14 februari 2021 19:57:21')
t <- as.data.frame(x)

How would you mutate x so it becomes a date in the format %d %B %Y? I've been looking into getting a substring but I don't seem to be able to get it to work.

strsplit(as.vector(t$x), " ")

I can't figure out how to correctly address each of the elements I need after the split so I can use it in dplyrs mutatue function.

1 Answers

Try below, I changed your data to English (my locale), should work fine with your locale (Dutch?), too:

# x <- "zondag 14 februari 2021 19:57:21"
x <- "sunday 14 february 2021 19:57:21"

#convert to date
strptime(x, "%A %d %B %Y %H:%M:%S")
# [1] "2021-02-14 19:57:21 GMT"

# now fix the format
format(strptime(x, "%A %d %B %Y %H:%M:%S"), "%d %B %Y")
# [1] "14 February 2021"
Related