Reputation: 475
I have a column with dates that are formatted like this:
yyyymm (e.g. 201809)
I want them to be formatted like this:
mm.yyyy (e.g. 09.2018)
I tried:
FF5factors$date <- strptime(FF5factors$date, format= "%Y%m")
format(FF5factors$date, format="%m.%Y")
But it only returns NA
values.
Upvotes: 0
Views: 1152
Reputation: 269431
Here are some alternatives. The question did not provide date in reproducible form so we assume the first line below although the first 4 alternatives will also work with date <- "201809"
and with date <- factor(201809)
.
date <- 201809
# 1
sub("(....)(..)", "\\2.\\1", date)
## [1] "09.2018"
# 2
library(zoo)
format(as.yearmon(format(date), "%Y%m"), "%m.%Y")
## [1] "09.2018"
# 3
paste(substr(date, 5, 6), substr(date, 1, 4), sep = ".")
## [1] "09.2018"
# 4
format(as.Date(paste0(date, "01"), "%Y%m%d"), "%m.%Y")
## [1] "09.2018"
# 5
sprintf("%02d.%d", date %% 100, date %/%100)
## [1] "09.2018"
Upvotes: 2
Reputation: 9485
What about:
d <- '201809'
format(as.Date(d,'%Y%M'),'%m.%Y')
[1] "09.2018"
Upvotes: 3