Search code examples
rtime-seriesrasterdata-conversion

How to read time series climate data (i.e., precipitation) without extension in R?


I have a file without any extension, which contain gridded daily temp_max(deg_c). The first two rows from the fourth column are indicates longitude and latitude respectively for each grid. Whereas First three column from 3rd row indicates year-month-day. And from the fourth column data are Tmax (Deg_c). For example please refer to following figure ScreenShot. I want to make raster time series of daily gridded Tmax (Deg_c). So, can you please guide me how to convert these data in R? Here is the link for the full data Temp_Max


Solution

  • Read the data, create a single variable for the date, and transpose to other values to get a data.frame arranged as lon, lat, z1, z2, ...

    d <- read.table("TMaxData")
    dates <- paste(d[,1], d[,2], d[,3], sep="-")[-c(1:2)]
    d <- t(d[, -c(1:3)])
    colnames(d) = c("lon", "lat", dates)
    

    Have a look

    d[1:3, 1:5]
    #       lon    lat 1951-1-1 1951-1-2 1951-1-3
    # V4 88.875 27.125    14.35    13.25    11.07
    # V5 89.125 26.875    20.76    19.39    17.88
    # V6 89.125 27.125    12.63    11.53     9.47
    

    Now we can coerce data.frame d to a SpatRaster, and set the time.

    library(terra)
    x <- rast(d, type="xyz", crs="+proj=longlat")
    time(x) <- as.Date(dates)
    
    x
    #class       : SpatRaster 
    #dimensions  : 6, 13, 23376  (nrow, ncol, nlyr)
    #resolution  : 0.25, 0.25  (x, y)
    #extent      : 88.75, 92, 26.75, 28.25  (xmin, xmax, ymin, ymax)
    #coord. ref. : +proj=longlat +datum=WGS84 +no_defs 
    #source      : memory 
    #names       : 1951-1-1, 1951-1-2, 1951-1-3, 1951-1-4, 1951-1-5, 1951-1-6, ... 
    #min values  :    -2.01,    -2.51,    -4.36,    -3.42,    -1.70,    -2.30, ... 
    #max values  :    21.55,    20.41,    18.82,    18.55,    21.70,    21.24, ... 
    #time (days) : 1951-01-01 to 2014-12-31 
    

    Have a look

    library(geodata)
    btn <- geodata::gadm("BTN", level=1, path=".")
    plot(x, 1)
    lines(btn)
    

    enter image description here