Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- library(stringr)
- format_to_date <- function(x){
- year <- str_extract(x, "^\d{4}")
- if (grepl("M", x)) {
- month <- str_pad(str_extract(x, "\d{1,2}$"), width = 2)
- paste0(year, "-", month, "-01")
- } else if (grepl("Q", x)) {
- month <- as.numeric(str_extract(x, "\d{1}$"))
- month <- month + (month - 1) * 3
- paste0(year, "-", month, "-01")
- } else{
- paste0(year, "-01-01")
- }
- }
- Dframe <-
- data.frame(string = c("2008M5", "2009Q3", "2011"),
- stringsAsFactors = FALSE)
- as.Date(vapply(Dframe$string, format_to_date, character(1)))
- df <- data.frame(Raw = c("2008M5", "2009Q3", "2011"))
- convertDate <- function(x) {
- res <- data.frame(DFreq = "Annual",
- Date = paste0("1/12/", x))
- if (length(grep("Q", x)) == 1) {
- foo <- unlist(strsplit(x, "Q"))
- res <- data.frame(DFreq = "Quarterly",
- Date = paste0("1/", as.numeric(foo[2]) * 3, "/", foo[1]))
- } else if (length(grep("M", x)) == 1) {
- foo <- unlist(strsplit(x, "M"))
- res <- data.frame(DFreq = "Monthly",
- Date = paste0("1/", foo[2], "/", foo[1]))
- }
- return(res)
- }
- res <- apply(df, 1, convertDate)
- res <- do.call("rbind", res)
- DFreq Date
- 1 Monthly 1/5/2008
- 2 Quarterly 1/9/2009
- 3 Annual 1/12/2011
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement