MODISTimeSeries.R 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. MODISTimeSeries <-
  2. function(Dir, Band, Simplify = FALSE)
  3. {
  4. # DEFINE
  5. NUM_METADATA_COLS <- 10
  6. WHICH_ID <- 6
  7. if(!file.exists(Dir)) stop("Character string input for Dir argument does not resemble an existing file path.")
  8. file.set <- list.files(path = Dir, pattern = ".asc")
  9. file.ids <- sapply(file.path(Dir, file.set), function(x)
  10. any(grepl(pattern = Band, x = read.csv(file = x, header = FALSE, as.is = TRUE)[ ,WHICH_ID]))
  11. )
  12. file.set <- file.set[file.ids]
  13. if(length(file.set) < 1) stop("No downloaded files found in the requested directory for the requested data band.")
  14. data.collector <- vector(mode = "list", length = length(file.set))
  15. ts.row.names <- vector(mode = "list", length = length(file.set))
  16. ts.col.names <- vector(mode = "list", length = length(file.set))
  17. nrow.recorder <- ncol.recorder <- numeric(length = length(file.set))
  18. for(i in 1:length(file.set)){
  19. data.file <- read.csv(file.path(Dir, file.set[i]), header = FALSE, as.is = TRUE)
  20. names(data.file) <- c("nrow", "ncol", "xll", "yll", "pixelsize", "row.id", "product.code", "MODIS.acq.date",
  21. "where", "MODIS.proc.date", 1:(ncol(data.file) - NUM_METADATA_COLS))
  22. data.file <- data.file[grepl(pattern = Band, x = data.file$row.id), ]
  23. data.collector[[i]] <- as.matrix(data.file[ ,(NUM_METADATA_COLS+1):ncol(data.file)])
  24. nrow.recorder[i] <- nrow(as.matrix(data.file[ ,(NUM_METADATA_COLS+1):ncol(data.file)]))
  25. ncol.recorder[i] <- ncol(as.matrix(data.file[ ,(NUM_METADATA_COLS+1):ncol(data.file)]))
  26. ts.col.names[[i]] <- paste(unique(data.file$where), "_pixel", 1:ncol.recorder[i], sep = "")
  27. ts.row.names[[i]] <- data.file$MODIS.acq.date
  28. colnames(data.collector[[i]]) <- ts.col.names[[i]]
  29. rownames(data.collector[[i]]) <- ts.row.names[[i]]
  30. }
  31. if(!Simplify) return(data.collector)
  32. if(!all(sapply(data.collector, nrow) == sapply(data.collector, nrow)[1])){
  33. cat('Simplify == TRUE, but not all tiles have the same number of rows so cannot be\n',
  34. 'simplified into one matrix. Returning data as an array instead.\n', sep = '')
  35. return(data.collector)
  36. } else {
  37. res <- matrix(nrow = max(nrow.recorder), ncol = sum(ncol.recorder))
  38. rownames(res) <- ts.row.names[[which(nrow.recorder == max(nrow.recorder))[1]]]
  39. colnames(res) <- unlist(ts.col.names)
  40. for(j in 1:length(data.collector)){
  41. res[1:nrow.recorder[j],(sum(1, ncol.recorder[1:j]) - ncol.recorder[j]):sum(ncol.recorder[1:j])] <-
  42. as.matrix(data.collector[[j]])
  43. }
  44. return(res)
  45. }
  46. }