**I have a raster with XY pixel coordinates which I want to convert to lat and long.**

```
class : RasterLayer
dimensions : 1617, 1596, 2580732 (nrow, ncol, ncell)
resolution : 1, 1 (x, y)
extent : 0, 1596, 0, 1617 (xmin, xmax, ymin, ymax)
coord. ref. : NA
data source : C:\janW1.png
names : janW1
values : 0, 255 (min, max)
```

I have calculated the lat/long coords using the formula specified here.

This has resulted in the following dataframe

```
heads(cords)
lat lon x y janW1
1 46.99401 -14.99122 0.5 1616.5 0
2 46.99401 -14.97367 1.5 1616.5 0
3 46.99401 -14.95611 2.5 1616.5 0
4 46.99401 -14.93856 3.5 1616.5 0
5 46.99401 -14.92100 4.5 1616.5 0
6 46.99401 -14.90345 5.5 1616.5 0
```

How can I over-write or create a duplicate raster with the spatial extent in lat/long instead of image coordinates (XY pixels)? Or is there an easier way to convert the pixels to lat/Lon?

## Code

```
library(raster)
test <- raster('janW1.png')
data_matrix <- rasterToPoints(test)
# Calculate longitude.
lonfract = data_matrix[,"x"] / (1596 - 1)
lon = -15 + (lonfract * (13 - -15))
# Calculate latitude.
latfract = 1.0 - (data_matrix[,"y"] / (1617 - 1))
Ymin = log(tan ((pi/180.0) * (45.0 + (47 / 2.0))))
Ymax = log(tan ((pi/180.0) * (45.0 + (62.999108 / 2.0))))
Yint = Ymin + (latfract * (Ymax - Ymin))
lat = 2.0 * ((180.0/pi) * (atan (exp (Yint))) - 45.0)
# Make single dataframe with XY pixels and latlon coords.
latlon <- data.frame(lat,lon)
tmp <- data.frame(data_matrix)
cords <- cbind(latlon, tmp)
```

`extent(r) <- extent(min(cords$lon), max(cords$lon), min(cords$lat), max(cords$lat))`

?note:`extent(r) <- extent(min(cords$lon), max(cords$lon), min(cords$lat), max(cords$lat))`

seems to produce slightly different lat/lon coordinates when compared to the`cords`

dataframe.