0

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.

Pete
  • 321
  • 4
  • 16
  • Can you provide a [minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610). The idea is to provide the **smallest** and **simplest** version of the problem. Instead of figuring it out on many hundred rows and columns its easier if there are onle 3 or so... That way you can help others to help you! – dario Feb 20 '20 at 20:08
  • Yes if I try this: ``` ## read in the raster raster <- raster("test.tif") ## Read in the coordinates lat1 <- read.csv("lat1.csv") lon1 <- read.csv("lon1.csv") xy <- expand.grid(lon1, lat1) # create new raster via SpatialPixelsDataFrame, copying the values from the original raster but supplying the new coordinates r2 <- raster(SpatialPixelsDataFrame(xy, data.frame(values(raster)))) ``` I get this error: Error in dimnames(X) <- list(dn[[1L]], unlist(collabs[nc > 0], use.names = FALSE)) : length of 'dimnames' [2] not equal to array extent – Pete Feb 21 '20 at 00:13

1 Answers1

0

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

CMB
  • 35
  • 5
  • Yes, I tried that, but the problem here is that the lat longs are in matrix format. I have no idea how to apply them to the raster. Any ideas? – Pete Feb 20 '20 at 22:36