How to create and stack rasters from XYZ dataframe using irregular gid (equviarea)?

96 views Asked by At

I have a equivearea grid of lat and lon data (grids are same area) and a dataframe with some environmental variables:

expl.var <- structure(list(SST = c(24.4812454115405, 30.3755130902902, 30.2892917343848, 
30.1874577574072, 30.0685523131313, 29.9304402875239), SSS = c(35.285267440907, 
35.1703847857361, 35.2065691838264, 35.2308472759306, 35.2436283833148, 
35.2454965615972), SO2 = c(0.216255172604181, 0.196075442330892, 
0.196369388021691, 0.196716810666302, 0.197111469500075, 0.197544240363149
), NPP = c(1.71847390840386e-07, 4.25195770217353e-07, 4.37328492599708e-07, 
4.51311105599561e-07, 4.67896786221831e-07, 4.88187112630607e-07
), SPH = c(7.95377102959121, 7.92617815403006, 7.92488307792535, 
7.92350716767386, 7.92209113652388, 7.9206946448589), Zeu = c(116.341237211261, 
97.4587276733914, 95.1907552617149, 92.4364488788246, 90.6108441294737, 
89.3163618175975), MLD = c(44.7432996720176, 66.6403655875183, 
65.9617895492943, 65.1298823394651, 64.2983405621902, 63.4020005717908
)), row.names = c(68L, 107L, 108L, 109L, 110L, 111L), class = "data.frame")

myRespXY <- structure(list(Lon = c(-179.75, -179.75, -179.75, -179.75, -179.75, 
-179.75), Lat = c(-24.26491, -4.04919, -3.54808, -3.04725, -2.54664, 
-2.04623)), row.names = c(68L, 107L, 108L, 109L, 110L, 111L), class = "data.frame")

I am trying to write a function that create a rastre for each environemnta variable, and then stack all the layers. I know how to do it on a regular grid:

stack_raster <- function(expl.var, myRespXY ) {
  r <- stack()
  for (col in 1:ncol(expl.var)) {
    ENV_col <- rasterFromXYZ(cbind(resp.xy, ENV[, col]), digits = 5 )
    r <- stack(r , ENV_col)
    
  }
  names(r) = colnames(expl.var)
  return(r)
}

r <- stack_raster(expl.var, myRespXY)

but since my grid is not regular, i get teh following error: Error in rasterFromXYZ(cbind(resp.xy, ENV[, col]), digits = 5) : y cell sizes are not regular

SO I wonder what function i can use to create and stack rasters on irregular grid

I did the following: it does teh job, but rasters are not created properly

stack_raster <- function(expl.var, myRespXY ) {
  r <- stack()
  for (col in 1:ncol(expl.var)) {
    
    r1= raster(x=as.matrix(myRespXY))
    s100<- as.matrix(cbind(myRespXY, expl.var[, col]))
    ENV_col <-rasterize(s100[, 1:2], r1, s100[,3], fun=mean)
    r <- stack(r , ENV_col)
    
  }
  names(r) = colnames(expl.var)
  return(r)
}
0

There are 0 answers