extractDate.R 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #' Extract Dates from (MODIS) Files
  2. #'
  3. #' @description
  4. #' This function helps to extract dates from a vector of files.
  5. #'
  6. #' @param files A \code{character} vector of filenames from which to extract
  7. #' dates. Alternatively, a \code{Raster*} with date information in its layer
  8. #' \code{\link[raster]{names}}.
  9. #' @param pos1,pos2 Start and end of date string in \code{files} as
  10. #' \code{integer}. If missing, positions are tried to be retrieved from a
  11. #' look-up table provided that 'files' comply with the MODIS standard naming
  12. #' convention.
  13. #' @param asDate \code{logical}. If \code{TRUE}, the result is converted to a
  14. #' \code{Date} object.
  15. #' @param format \code{character}, date format. Used only if \code{asDate = TRUE}.
  16. #' Defaults to MODIS date style (i.e., \code{"\%Y\%j"} for year and julian day).
  17. #' See \code{\link{strptime}} for modifications.
  18. #'
  19. #' @return
  20. #' A \code{list} with the following entries: 'inputLayerDates', 'pos1', 'pos2',
  21. #' 'asDate' and, optionally, 'format'. If \code{asDate = FALSE},
  22. #' 'inputLayerDates' are represented as \code{character}, else as \code{Date}.
  23. #'
  24. #' @author
  25. #' Matteo Mattiuzzi
  26. #'
  27. #' @examples
  28. #' # example on HDF files
  29. #' files <- c("MOD13Q1.A2010209.h18v03.005.2010239071130.hdf",
  30. #' "MOD13Q1.A2010225.h18v03.005.2010254043849.hdf")
  31. #' extractDate(files)
  32. #' extractDate(files, asDate = TRUE)
  33. #'
  34. #' # on any other file
  35. #' files <- c("Myfile_20010101.XXX", "Myfile_20010115.XXX", "Myfile_20010204.XXX")
  36. #' extractDate(files, pos1 = 8, pos2 = 15)
  37. #' extractDate(files, pos1 = 8, pos2 = 15, asDate = TRUE, format = "%Y%m%d")
  38. #'
  39. #' @export extractDate
  40. #' @name extractDate
  41. extractDate <- function(files, pos1, pos2, asDate = FALSE, format = "%Y%j")
  42. {
  43. if (inherits(files, "Raster")) {
  44. files <- names(files)
  45. }
  46. files <- basename(files)
  47. ## if any position indication is missing, try to retrieve it from look-up table
  48. if (any(missing(pos1), missing(pos2))) {
  49. ids = positionIndication(files)
  50. pos1 = ids[[1]]; pos2 = ids[[2]]
  51. }
  52. date <- sapply(files,function(x){
  53. substr(x, pos1, pos2)
  54. })
  55. if(asDate)
  56. {
  57. date <- as.Date(date, format=format)
  58. return(list(inputLayerDates = date, pos1=pos1, pos2=pos2, asDate = asDate, format=format))
  59. } else
  60. {
  61. return(list(inputLayerDates = date, pos1 = pos1, pos2 = pos2, asDate = asDate))
  62. }
  63. }