Search code examples
rdataframegridgeospatialraster

Irregular grid from dataframe to raster in R


I have extracted data at points (lat& lon) at irregular interval. Can a irregular grid be created from the extract dataframe? I do not intend to interpolate the data and keep as it is. I am getting an error trying to create a gridded dataset-

      lon     lat   temp
1  8.5261 50.0223 293.40
2 78.4390 17.2290 295.90
3  8.6350 49.9290 282.88
spg <- df
coordinates(spg) <- ~ lon + lat
gridded(spg) <- TRUE

Error in points2grid(points, tolerance, round) : dimension 1 : coordinate intervals are not constant


Solution

  • We could round the values

    library(sp)
    spg[1:2] <- lapply(spg[1:2], function(x) as.numeric(round(x)))
    coordinates(spg) <- ~ lon + lat
    gridded(spg) <- TRUE
    

    -output

    > spg
    Object of class SpatialPixelsDataFrame
    Object of class SpatialPixels
    Grid topology:
        cellcentre.offset cellsize cells.dim
    lon                 9       69         2
    lat                17       33         2
    SpatialPoints:
      lon lat
    1   9  50
    2  78  17
    3   9  50
    Coordinate Reference System (CRS) arguments: NA 
    
    Data summary:
          temp      
     Min.   :282.9  
     1st Qu.:288.1  
     Median :293.4  
     Mean   :290.7  
     3rd Qu.:294.6  
     Max.   :295.9  
    

    data

    df <- structure(list(lon = c(8.5261, 78.439, 8.635), lat = c(50.0223, 
    17.229, 49.929), temp = c(293.4, 295.9, 282.88)),
     class = "data.frame", row.names = c("1", 
    "2", "3"))