Search code examples
rimageinterpolationsurfacer-grid

Create a surface from "pre-gridded" points


I have a large data.frame which has 3 variables Longitude, Latitudeand Temp.

The data is arranged so that it is regularly spaced on a "grid" of 1/4 degree - so that dput(head(dat)) gives:

structure(list(Longitude = c(0.125, 0.375, 0.625, 0.875, 1.125, 
1.375), Latitude = c(0.125, 0.125, 0.125, 0.125, 0.125, 0.125
), Temp = c(25.2163, 25.1917, 25.1593, 25.125, 25.0908, 25.0612
)), .Names = c("Longitude", "Latitude", "Temp"), row.names = c(NA, 
6L), class = "data.frame").

I am having problems re-arranging it to the required format.

I would like to create a regular surface object (typically a list), where x and y are the grid values and z is a corresponding matrix of the surface. This is the usual format used by persp, contour, imageetc.

Using this surface object I will could then be able to easily interpolate to a matrix of locations using interp.surffrom the fieldspackage.

Any suggestions would be great.


Solution

  • Suppose your data is like

    set.seed(123)
    d <- data.frame(lon=rep(seq(0,1,0.25), times=5),
               lat=rep(seq(0,1,0.25), each=5),
               temp=sample(1:25, 25, replace=TRUE))
    head(d, 8)
    #    lon  lat temp
    # 1 0.00 0.00    8
    # 2 0.25 0.00   20
    # 3 0.50 0.00   11
    # 4 0.75 0.00   23
    # 5 1.00 0.00   24
    # 6 0.00 0.25    2
    # 7 0.25 0.25   14
    # 8 0.50 0.25   23
    

    We create a z matrix that represent the values for each point in the grid. We then put the locations of the grid lines (x and y) into a list, together with z.

    library(reshape2)
    z <- acast(d, lat~lon, value.var="temp")
    X <- list(x=sort(unique(d$lon)), 
              y=sort(unique(d$lat)), 
              z=z)
    
    image(X, col=gray.colors(25))
    with(d, text(lon, lat, labels=temp))
    

    enter image description here

    Also see Change Lat & Lon vectors to matrix in R.