Advertisement
Guest User

Untitled

a guest
Apr 18th, 2014
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. df$date = as.Date(df$excel.date, format = "%d/%m/%Y")
  2.  
  3. head(df$date)
  4. [1] NA NA NA "0006-01-05" NA NA
  5.  
  6. 7/28/05
  7. 7/28/05
  8. 12/16/05
  9. 5/1/06
  10. 4/21/05
  11.  
  12. head(df$excel.date)
  13. [1] 7/28/05 7/28/05 12/16/05 5/1/06 4/21/05 1/25/07
  14. 1079 Levels: 1/1/00 1/1/02 1/1/97 1/10/96 1/10/99 1/11/04 1/11/94 1/11/96 1/11/97 1/11/98 ... 9/9/99
  15.  
  16. str(df)
  17. .
  18. .
  19. $ excel.date : Factor w/ 1079 levels "1/1/00","1/1/02",..: 869 869 288 618 561 48 710 1022 172 241 ...
  20.  
  21. > as.Date("13/04/2014", format= "%d/%m/%Y")
  22. [1] "2014-04-13"
  23. > as.Date(factor("13/04/2014"), format= "%d/%m/%Y")
  24. [1] "2014-04-13"
  25. > as.Date(factor("13/04/14"), format= "%d/%m/%Y")
  26. [1] "14-04-13"
  27. > as.Date(factor("13/04/14"), format= "%d/%m/%y")
  28. [1] "2014-04-13"
  29.  
  30. function (x, ...) as.Date(as.character(x), ...)
  31.  
  32. x <- c("7/28/05", "7/28/05", "12/16/05", "5/1/06", "4/21/05", "1/25/07")
  33.  
  34. repairExcelDates <- function(x, yearcol=3, fmt="%m/%d/%Y") {
  35. x <- do.call(rbind, lapply(strsplit(x, "/"), as.numeric))
  36. year <- x[,yearcol]
  37. if(any(year>99)) stop("dont'know what to do")
  38. x[,yearcol] <- ifelse(year <= as.numeric(format(Sys.Date(), "%Y")), year+2000, year + 1900)
  39. # if year <= current year then add 2000, otherwise add 1900
  40. x <- apply(x, 1, paste, collapse="/")
  41. as.Date(x, format=fmt)
  42. }
  43.  
  44. repairExcelDates(x)
  45. # [1] "2005-07-28" "2005-07-28" "2005-12-16" "2006-05-01" "2005-04-21"
  46. # [6] "2007-01-25"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement