Search code examples
rtime-series

Convert Modis doy to datetime in R


I would like to analyze a modis ndvi time series in R. I have 105 files (2000-2020) and would like to start by extracting the time information. However, I am struggling with the code as I am new to R. They start in May 2000.

I tried the following code and get a list of the correct day and month as a result but wrong year values (only 2000).

files <- list.files()

dates = foreach(i=1:length(files)) %do% { 
  as.Date(as.integer(substr(files[[i]], 39, 41)), origin = "1999-12-31") 
}

time_df <- data.frame(Date = unlist(dates))
#This is how my files look:

> head(files) 
[1] "MOD13Q1.006__250m_16_days_NDVI_doy2000113_aid0001.tif" 
[2] "MOD13Q1.006__250m_16_days_NDVI_doy2000129_aid0001.tif" 
[3] "MOD13Q1.006__250m_16_days_NDVI_doy2000145_aid0001.tif" 
[4] "MOD13Q1.006__250m_16_days_NDVI_doy2000161_aid0001.tif" 
[5] "MOD13Q1.006__250m_16_days_NDVI_doy2000177_aid0001.tif" 
[6] "MOD13Q1.006__250m_16_days_NDVI_doy2001113_aid0001.tif"

with the presented code i didnt get the correct year values out of my modis data


Solution

  • This is what I've done:

    1. The file_list can be taken from your directory
    2. Help on dates formatting is included with in the base package.
    file_list <- c("MOD13Q1.006__250m_16_days_NDVI_doy2000113_aid0001.tif",
                   "MOD13Q1.006__250m_16_days_NDVI_doy2000129_aid0001.tif",
                   "MOD13Q1.006__250m_16_days_NDVI_doy2000145_aid0001.tif",
                   "MOD13Q1.006__250m_16_days_NDVI_doy2000161_aid0001.tif",
                   "MOD13Q1.006__250m_16_days_NDVI_doy2000177_aid0001.tif",
                   "MOD13Q1.006__250m_16_days_NDVI_doy2001113_aid0001.tif")
    
    find_date <- function(file_name) {
      year <- substr(file_name, 35, 38)
      num_days <- as.numeric(substr(file_name, 39, 41))
      as.Date(num_days, origin = paste0(year, "-01-01"))
    }
    
    find_date(file_list)
    
    # [1] "2000-04-23" "2000-05-09" "2000-05-25" "2000-06-10" "2000-06-26" "2001-04-24"