I have a string as follows
11MAY2018:00:00:00.000 Can this be converted to the following formats
i) 11-May-2018
ii) May-2018 or 05-2018
You can use lubridate package to turn your string into a date format and then use some functions like year, month, day to extract relevant information and combine them using paste0:
library(lubridate) x = "11MAY2018:00:00:00.000" y = dmy_hms(x) paste0(c(day(y),as.character(month(y, label = T)),year(y)), collapse = "-") # [1] "11-May-2018" paste0(c(as.character(month(y, label = T)),year(y)), collapse = "-") # [1] "May-2018" paste0(c(month(y),year(y)), collapse = "-") # [1] "5-2018" format(y, format = "%d-%b-%Y"), format(y, format = "%b-%Y"), format(y, format = "%m-%Y")It should work as well:
str<-"11MAY2018:00:00:00.000" dt<-substring(str, c(1), c( 9)) as.Date(dt,format='%d%b%Y') substring(str, 1, 9), without the c(.). But your output seems to be "2020-05-11". It works with as.Date(dt,format='%d%b%Y') (capital Y)2020. Do you have any idea?%ylooks for only a two-digit year, you need %Y as @AntoniosK already said"11SEP2018:00:00:00.000", and it works well. So, why do you think, it does not work for different monthes?