R: How to get latitudes and longitudes from a RasterLayer?
you need to actually reproject the raster into a geographic (decimal degrees) projection using "projectRaster" or "spTransform". Also look at CRS sp definitions that specify your desired projection string. The example in the help for the "projectRaster" is quite clear in how to do this.
If you coerce your raster data into a SpatialPointsDataFrame object then you would use "spTransform" and pull the coordinates from the @coordinates slot and add them to the data.frame in the @data slot. Here is an example of what that would look like.
library(raster)
library(rgdal) # for spTransform
# Create data
r <- raster(ncols=100, nrows=100)
r[] <- runif(ncell(r))
crs(r) <- "+proj=lcc +lat_1=48 +lat_2=33 +lon_0=-100 +ellps=WGS84"
projection(r)
# Convert raster to SpatialPointsDataFrame
r.pts <- rasterToPoints(r, spatial=TRUE)
proj4string(r.pts)
# reproject sp object
geo.prj <- "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"
r.pts <- spTransform(r.pts, CRS(geo.prj))
proj4string(r.pts)
# Assign coordinates to @data slot, display first 6 rows of data.frame
r.pts@data <- data.frame(r.pts@data, long=coordinates(r.pts)[,1],
lat=coordinates(r.pts)[,2])
head(r.pts@data)
I should note that it is not good practice to convert rasters to a vector object class and negates the advantages of the raster package providing memory safe processing. It is often prudent to really think about your problem and assess if you are approaching it correctly. If the OP had provided context as to why they need [x,y] coordinates for every cell, the forum community may have been able to provide computational alternatives that would keep the problem in a raster environment.
Get the coordinates of the cell centres and create a Spatial object:
spts <- rasterToPoints(r, spatial = TRUE)
Transform the points to your desired target:
library(rgdal)
llprj <- "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0"
llpts <- spTransform(spts, CRS(llprj))
The values are already copieds as columns on this SpatialPointsDataFrame.
print(llpts)
Now to finish, get a data.frame:
x <- as.data.frame(llpts)
There's a general implementation of this in the SGAT package, see function lonlatFromCell
here:
https://github.com/SWotherspoon/SGAT/blob/master/R/Raster.R