Advertisement
Guest User

Untitled

a guest
Sep 22nd, 2017
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. library(stringr)
  2.  
  3. format_to_date <- function(x){
  4. year <- str_extract(x, "^\d{4}")
  5. if (grepl("M", x)) {
  6. month <- str_pad(str_extract(x, "\d{1,2}$"), width = 2)
  7. paste0(year, "-", month, "-01")
  8. } else if (grepl("Q", x)) {
  9. month <- as.numeric(str_extract(x, "\d{1}$"))
  10. month <- month + (month - 1) * 3
  11. paste0(year, "-", month, "-01")
  12. } else{
  13. paste0(year, "-01-01")
  14. }
  15. }
  16.  
  17. Dframe <-
  18. data.frame(string = c("2008M5", "2009Q3", "2011"),
  19. stringsAsFactors = FALSE)
  20.  
  21. as.Date(vapply(Dframe$string, format_to_date, character(1)))
  22.  
  23. df <- data.frame(Raw = c("2008M5", "2009Q3", "2011"))
  24.  
  25. convertDate <- function(x) {
  26. res <- data.frame(DFreq = "Annual",
  27. Date = paste0("1/12/", x))
  28. if (length(grep("Q", x)) == 1) {
  29. foo <- unlist(strsplit(x, "Q"))
  30. res <- data.frame(DFreq = "Quarterly",
  31. Date = paste0("1/", as.numeric(foo[2]) * 3, "/", foo[1]))
  32. } else if (length(grep("M", x)) == 1) {
  33. foo <- unlist(strsplit(x, "M"))
  34. res <- data.frame(DFreq = "Monthly",
  35. Date = paste0("1/", foo[2], "/", foo[1]))
  36. }
  37. return(res)
  38. }
  39. res <- apply(df, 1, convertDate)
  40. res <- do.call("rbind", res)
  41.  
  42. DFreq Date
  43. 1 Monthly 1/5/2008
  44. 2 Quarterly 1/9/2009
  45. 3 Annual 1/12/2011
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement