问题
Given raster object r, how can I create a new raster with the same extent and resolution, with cell values equal to the latitude (or longitude) of the corresponding cell in r?
For example, r might look like:
r <- raster(matrix(runif(100), ncol=10))
回答1:
If your question is about create a new raster object which has the same extent and resolution of another raster object you can use command template
template is Raster* or Extent object used to set the extent (and CRS in case of a Raster* object). If not NULL, arguments xmn, xmx, ymn, ymx and crs (unless template is an Extent object) are ignored
r <- raster(matrix(runif(100), ncol=10))
r1 <- raster(x, template=r)
回答2:
You can use the init function
library(raster)
r <- raster(nrow=10, ncol=10)
lon <- init(r, 'x')
lat <- init(r, 'y')
回答3:
A simple way to do this is to (1) duplicate raster r, (2) extract its coordinates with coordinates, and (3) assign the longitudes or latitudes to the new raster objects' cells.
For example, using your r:
library(raster)
r <- raster(matrix(runif(100), ncol=10))
lat <- lon <- r
xy <- coordinates(r)
lon[] <- xy[, 1]
lat[] <- xy[, 2]
And here's what they look like:
plot(setNames(stack(r, lon, lat), c('r', 'lon', 'lat')))
回答4:
If anyone's just looking for a global raster of latitudes to download, and less interested in how it was made, I've posted one here:
Positive and negative values (90S is -90): https://drive.google.com/open?id=1fV1pnvlzi2PTJM7e6zx0S5IMP1mg09m-
Just positive values (90S is 90): https://drive.google.com/open?id=1ibyNAp1c0E_DY9bFF-1gJw0vizKRmDUT
These were posted at .1 degree intervals.
Python code to generate:
import rasterio
import numpy as np
cellsize = .1
xedges = np.arange(-180,180,cellsize)
yedges = np.arange(90,-90,-cellsize)
XI, YI = np.meshgrid(xi,yi)
t = rasterio.transform.from_origin(xedges[0], yedges[0], cellsize, cellsize)
with rasterio.open('latitude.tif', 'w', driver='GTiff',
height=YI.shape[0], width=YI.shape[1],
count=1, dtype=np.float32, transform=t) as src:
src.write(YI.astype(np.float32), 1)
with rasterio.open('latitude_abs.tif', 'w', driver='GTiff',
height=YI.shape[0], width=YI.shape[1],
count=1, dtype=np.float32, transform=t) as src:
src.write(np.abs(YI).astype(np.float32), 1)
来源:https://stackoverflow.com/questions/35580730/raster-of-latitudes-and-longitudes