简体   繁体   中英

How do I replace the XY coordinates of a raster in R?

I realize that the title of this question is similar to another question, but the solution there does not work for me.

I have a raster file. I have a matrix of latitudes and a matrix of longitudes. I want to replace the x and y coordinates of the raster file with those in the two matrices.

I have uploaded example files here. There are three files, one if a raster (GeoTIFF) and two matrices of longitudes and latitudes.



## read in the raster
raster <- raster("test.tif")

## Read in the coordinates 
lat1 <- read.csv("lat1.csv")
lon1 <- read.csv("lon1.csv")

raster$lon <- lon1 ##??? no clue
raster$lat <- lat1 ##???



https://www.dropbox.com/sh/0lsdgo3mk95hua8/AAA9fMuCo2XZmu50U6QFq4cEa?dl=0

What is an easy way to do this? Can I use the same methods on a RasterBrick?

I have tried many things, I cannot find how to replace the coordinates.

Any help would be appreciated.

Something like this might help:

library(raster)
library(rgdal)

# starting raster:
r<- raster(matrix(1:100, nrow = 10))

# new coordinates:
x <- 51:60
y <- 21:30
xy <- expand.grid(x, y)

# create new raster via SpatialPixelsDataFrame, copying the values from the original raster but supplying the new coordinates
r2 <- raster(SpatialPixelsDataFrame(xy, data.frame(values(r))))

# plot to have a look:
par(mfrow = c(1,2))
plot(r)
plot(r2)

Note that raster takes xy coordinates as the centre of the pixel, giving an extent that might surprise you:

extent(r2)

But you can easily adjust to whatever you want

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM