I'm (trying to) do operations on pairs of geographical points. I have the coordinates of my points in WGS84, and I need to have them in the Lambert 2 Extended CRS (LIIE). I'm trying to do it using rgdal.
Here's what I'm doing :
library("rgdal")
library("sp")
# Loading CRS
WGS84<-"+proj=longlat +ellps=WGS84 +towgs84=0,0,0,-0,-0,-0,0 +no_defs"
LIIE<-"+proj=lcc +lat_1=46.8 +lat_0=46.8 +lon_0=0 +k_0=0.99987742 +x_0=600000 +y_0=2200000 +a=6378249.2 +b=6356515 +towgs84=-168,-60,320,0,0,0,0 +pm=paris +units=m +no_defs"
# Loading the pairs of points
matrix<-read.table(file="file_with_coordinates.csv", header=TRUE, sep=";", stringsAsFactors = F)
The columns of matrix are as follow : origin_id, destination_id, or_lon, or_lat, de_lon, de_lat. Obviously, only the last 4 columns need to be transformed from WGS84 to LIIE.
I'm able to transform the coordinates by doing this :
matrix_sp<-SpatialPoints(coords = od_matrix[,c("de_lon","de_lat","or_lon","or_lat")],proj4string = CRS(WGS84))
matrix_sp_liie<-spTransform(od_matrix_sp, CRSobj = CRS(LIIE))
matrix_liie<-data.frame(matrix_sp_liie)
However, I therefore lose the origin and destination IDs... (And I don't have anything left that could allow me to merge back together matrix_liie with the origin/destination ids in matrix_sp).
I tried this (it's basically the same code but with destination_id and oririgin_id included in the first line), but I couldn't really get to something interesting (I get a Error in .local(obj, ...) : cannot derive coordinates from non-numeric matrix error).
od_matrix_sp<-SpatialPoints(coords = od_matrix[,c("destination_id","oririgin_id","de_lon","de_lat","or_lon","or_lat")],proj4string = CRS(WGS84))
matrix_sp_liie<-spTransform(od_matrix_sp, CRSobj = CRS(LIIE))
matrix_liie<-data.frame(matrix_sp_liie)
Any idea on how I could achieve this ?
Thanks.
Sample from CSV :
origin_id destination_id or_lon or_lat de_lon de_lat
123_a 005 3.88 45.6 1.56 46.7
123_b 006 5.10 41.1 2.4 42.6
Hi it's sp that does the conversion, and you can do that without use SpatialPoints, just specify which columns in matrix are the coordinates with coordinates, here an example :
library("sp")
# Some coordinates
latlong <- data.frame(
ID = 1:8,
LETTERS = LETTERS[1:8],
lon = runif(n = 8, min = 2.0798, max = 2.9931),
lat = runif(n = 8, min = 48.6823, max = 49.0698)
)
# Loading CRS
WGS84<-"+proj=longlat +ellps=WGS84 +towgs84=0,0,0,-0,-0,-0,0 +no_defs"
LIIE<-"+proj=lcc +lat_1=46.8 +lat_0=46.8 +lon_0=0 +k_0=0.99987742 +x_0=600000 +y_0=2200000 +a=6378249.2 +b=6356515 +towgs84=-168,-60,320,0,0,0,0 +pm=paris +units=m +no_defs"
# Set which var are the coord
coordinates(latlong) <- c("lon", "lat")
# Set the proj
proj4string(latlong) <- CRS(WGS84)
# Convert
latlon_conv <- spTransform(x = latlong, CRSobj = CRS(LIIE))
# Back to data.frame
latlon_conv <- as.data.frame(latlon_conv)
latlon_conv # maybe change columns names...
# ID LETTERS lon lat
# 1 1 A 632441.1 2440172
# 2 2 B 633736.7 2434332
# 3 3 C 586298.5 2411320
# 4 4 D 645107.6 2410351
# 5 5 E 642454.6 2443052
# 6 6 F 628371.7 2448833
# 7 7 G 625445.7 2436324
# 8 8 H 624509.7 2443864
EDIT : After seeing #Spacedman comment, you can effectively use SpatialPointsDataFrame instead of SpatialPoints :
latlong.sp <- SpatialPointsDataFrame(
coords = latlong[, c("lon", "lat")],
data = latlong[, c("ID", "LETTERS")],
proj4string = CRS(WGS84)
)
latlon_conv <- spTransform(x = latlong.sp, CRSobj = CRS(LIIE))
latlon_conv.df <- as.data.frame(latlon_conv)
latlon_conv.df
Related
I want to plot the utilization distributions of two animals on a spatial map background and calculate area overlap. However, for some reason, although both layers have the same projection, one is off (plotted too far to the east). Consequently, any overlap I calculate then is incorrect.
So my question is what causes this issue and how can I fix this?
Below are my two rasters, transformed to SpatialPolygons so that I could use gIntersection() to calculate overlap. Note that while p1 plots just fine, p2 does not.
p1 <- class : SpatialPolygons
features : 549
extent : 667950.6, 672950.6, 2840181, 2853981 (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=17 +datum=WGS84 +units=m +no_defs
p2 <- class : SpatialPolygons
features : 257
extent : 670158.7, 673958.7, 2839623, 2851623 (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=17 +datum=WGS84 +units=m +no_defs
Below pic shows how the polygons are currently plotted. p1 is depicted in green, and p2 is in red.
Desired plotting location for p2 should look like this (this plot is created in ggplot2 from the same raster file):
I thought maybe it was because the extents are so different. So I extended the areas of both rasters to the same extent, after which I converted them to polygons and plotted. But this does not solve anything.
EDIT: rasters r1 and r2 that can be converted to SpatialPolygons using as(x, 'SpatialPolygons') can be downloaded here and here.
EDIT 2: The crs for both rasters should be:
"+proj=utm +zone=17 +datum=WGS84 +units=m +no_defs"
EDIT 3: If it helps, the two rasters in question were generated by combining 2 sub-region rasters (central and north) after first extending the spatial extents of each raster to the spatial extent shared by both rasters and then rescaling to range from 0 to 1. However, some other rasters (not included here) are made up from 3 sub-region rasters. I don't know why this could matter, as the projections of the rasters are the same, so therefore should lead to correct spatial plots?
EDIT 4: Region rasters that were used to create r1 can be downloaded here and here. Similarly, region rasters for r2 are here and here.
EDIT 5: Below the code that i used to generate the output. Sorry for not introducing this earlier. r1 and r2 provided in the links are identical to r1.recl and r2.recl where the 0's have been replaced by NA.
library(magrittr)
aeqd.crs <- "+proj=aeqd +lat_0=25.6871 +lon_0=-79.29336 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs" #aeqd is original CRS
UTMstring <- "+proj=utm +zone=17 +datum=WGS84 +units=m +no_defs" # crs of study site shapefile
r1 = raster("r1")
proj4string(r1) <- CRS(aeqd.crs)
r1 %<>% raster::setMinMax()
r1 <- projectRaster(r1, crs = UTMstring)
r1[is.na(r1)] <- 0
r1 <- r1 / max(r1#data#values)
recl <- matrix(data = c(0, 0.05, 0,
0.05, 1, 1), ncol = 3, byrow = T)
r1.recl <- reclassify(r1, recl)
r1.recl[r1.recl == 0] <- NA
r2 = raster("r2")
proj4string(r2) <- CRS(aeqd.crs)
r2 %<>% raster::setMinMax()
r2 <- projectRaster(r2, crs = UTMstring)
r2[is.na(r2)] <- 0
r2 <- r2 / max(r2#data#values)
r2.recl <- reclassify(r2, recl)
r2.recl[r2.recl == 0] <- NA
# convert rasters to spatial polygons; vector shapes give access to spatial tools in the {rgeos} package
p1 <- as(r1.recl, 'SpatialPolygons')
p2 <- as(r2.recl, 'SpatialPolygons')
overlap <- gIntersection(p1, p2) # Creates raster
# Calculate common area
plot(p1, col = "green")
plot(p2, col = "red", add = TRUE)
plot(overlap, col = "orange", add = TRUE)
# calculate area of overlap (in m2)
common.area <- gArea(overlap) / (1000^2)
common.area
[1] 92716.54
Here are two approaches to compute overlap with your data.
Your data
library(terra)
prj <- "+proj=utm +zone=17 +datum=WGS84 +units=m +no_defs"
r1 <- rast("r1.asc")
crs(r1) <- prj
r2 <- rast("r2.asc")
crs(r2) <- prj
The "raster" approach
e <- union(ext(r1), ext(r2))
x1 <- extend(r1, e)
x2 <- resample(r2, x1) + 1
y <- sum(c(x1, x2), na.rm=TRUE)
a <- cellSize(y)
zonal(a, y, "sum")
# sum area
#1 1 21881870.89
#2 2 10200711.13
#3 3 80006.73
Where "1" is the area covered by species r1, "2" by r2 and "3" by both.
You can also assume a fixed nominal resolution. In this case that is only a little less precise (but that is not always the case)
f <- freq(y)
f$area <- f$count * prod(res(y))
f[,-1]
# value count area
#1 1 547 21880000
#2 2 255 10200000
#3 3 2 80000
The "vector" approach
p1 <- as.polygons(r1)
p2 <- as.polygons(r2)
p <- union(p1, p2)
p$area <- expanse(p)
data.frame(p)
# r1 r2 area
#1 1 1 92724.32
#2 1 NA 21869156.44
#3 NA 1 10187993.21
You could also do
intersect(p1, p2) |> expanse()
#[1] 92724.32
The results are similar for the raster and vector approach, but not the same. This is because the raster data are not aligned, which suggests that you could improve how these were created.
Plotting the two species shows the same pattern you have
p1$sp <- "1"
p2$sp <- "2"
p <- rbind(p1, p2)
plot(p, "sp")
And I can more-or-less reproduce r1 and r2 (but I need to guess things, in the future please describe your procedures with code, not with natural language) :
bn = rast("bull_North.asc")
bs = rast("bull_South.asc")
rn = rast("reef_North.asc")
rs = rast("reef_South.asc")
b2 = bn + bs
r2 = rn + rs
e <- intersect(ext(b2), ext(r2))
b <- crop(b2, e)
r <- crop(r2, e)
b <- ifel(b>0.05, 1, NA)
r <- ifel(r>0.05, 1, NA)
plot(b, col="blue")
plot(r, col="red", add=TRUE)
So, clearly the problem is already present in the original data.
So we've got this working without accounting for the projection issue. The issue is where (and how) to best add the re-projection so that the function returns the value in km rather than the current degrees:
library(raster)
library(purrr)
library(sf)
#example presence data from model
r1 <- raster(nrow=360, ncol=720)
crs(r1) <- "+proj=longlat +datum=WGS84 +no_defs"
values(r1) <- rbinom(ncell(r1), 2, 0.01)
r1_points <- rasterToPoints(r1)
r1_df <- data.frame(r1_points)
r1_presence <- r1_df %>% dplyr::filter(layer==1)
#example survey data
survey_points <- cbind(rnorm(50) * 5 + 10, rnorm(50) + 50)
pt2 <- st_multipoint(cbind(survey_points[,1], survey_points[,2]))
#distance between each modelled presence (pt1) and survey point (pt2)
get_distances <- function(i, pt2, df) {
pt1 <- st_multipoint(cbind(df[i, 1], df[i, 2]), dim = "XY")
a <- st_nearest_points(pt1, pt2)
return(st_length(a))
}
#loop for all modelled presences
output <- map_dbl(1:nrow(r1_presence), get_distances, pt2, r1_presence)
Ideally a perfect answer would expand the get_distances function to add a new option that does the appropriate re-projection and returns the value in km.
There may be a few different approaches here and I'm curious what people will come up with.
The premise of your question is wrong. You should generally not project your data to compute distances; projections distort so the distance will not be very precise. This is especially true if your data has a large spatial extent.
Approaches to compute the nearest distance may vary, for example depending on how many points you have. But in this example you can just use brute force and compute all distances
library(raster)
r1 <- raster(nrow=360, ncol=720)
crs(r1) <- "+proj=longlat +datum=WGS84 +no_defs"
set.seed(1)
values(r1) <- rbinom(ncell(r1), 2, 0.01)
r1_presence <- rasterToPoints(r1, fun=function(x)x==1)
survey_points <- cbind(rnorm(50) * 5 + 10, rnorm(50) + 50)
d <- pointDistance(r1_presence[,1:2], survey_points, lonlat=TRUE)
mind <- apply(d, 1, min)
head(mind)
#[1] 4268674 4261209 4258182 4254560 4220200 4218188
With terra v 1.2-0 (currently the development version, that you can install from github) you can do
library(terra)
#terra version 1.2.0
from <- vect(r1_presence[,1:2], crs="+proj=longlat +datum=WGS84")
to <- vect(survey_points, crs="+proj=longlat +datum=WGS84")
x <- nearest(from, to)
x
# class : SpatVector
# geometry : points
# dimensions : 5158, 7 (geometries, attributes)
# extent : -2.271833, 22.16701, 48.51506, 51.98087 (xmin, xmax, ymin, ymax)
# coord. ref. : +proj=longlat +datum=WGS84 +no_defs
# names : from_id from_x from_y to_id to_x to_y distance
# type : <num> <num> <num> <num> <num> <num> <num>
# values : 1 -171.2 89.75 25 8.752 51.98 4.269e+06
# 2 -128.2 89.75 25 8.752 51.98 4.261e+06
# 3 -119.8 89.75 25 8.752 51.98 4.258e+06
I am having a bit of a problem converting .csv files into raster in R... My .csv file contains coordinates (long and lat) radius (in deg) and site type. I was able to convert the coordinates into raster and was able to plot the circles using st_buffer() but I am facing two problems:
I can't convert the circles into a raster... I tried with rasterize() and fasterize() and both did not work all I'm getting is an empty raster layer
I can't seem to classify the coordinates and circles according to the site type
Any idea of what I might be doing wrong? and how can I classify my circles?
Thank you in advance!
Here is the code I used:
> head(sp_csv_data)
Longitude Latitude Radius Site_Type
1 -177.87567 -24.715167 10 MIG
2 -83.21360 14.401800 1 OBS
3 -82.59392 9.589192 1 NES
4 -82.41060 9.492750 1 NES;BRE
5 -81.17555 7.196750 5 OBS
6 -80.95770 8.852700 1 NES
##Projection systems used
rob_pacific <- "+proj=robin +lon_0=180 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs" # Best to define these first so you don't make mistakes below
longlat <- "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"
####Converting to raster####
# Creating a empty raster at 0.5° resolution (you can increase the resolution to get a better border precision)
rs <- raster(ncol = 360*2, nrow = 180*2)
rs[] <- 1:ncell(rs)
crs(rs) <- CRS(longlat)
##Converting to raster
sp_raster <- rasterize(sp_csv_data[,1:2], rs, sp_csv_data[,3])
# Resampling to make sure that it's in the same resolution as sampling area
sp_raster <- resample(sp_raster, rs, resample = "ngb")
#converting into an sf spatial polygon dataframe
sp_raster <- as(sp_raster, "SpatialPolygonsDataFrame")
species_sp <- spTransform(sp_raster, CRS(longlat))
# Define a long & slim polygon that overlaps the meridian line & set its CRS to match that of world
polygon <- st_polygon(x = list(rbind(c(-0.0001, 90),
c(0, 90),
c(0, -90),
c(-0.0001, -90),
c(-0.0001, 90)))) %>%
st_sfc() %>%
st_set_crs(longlat)
# Transform the species distribution polygon object to a Pacific-centred projection polygon object
sp_robinson <- species_sp %>%
st_as_sf() %>%
st_difference(polygon) %>%
st_transform(crs = rob_pacific)
# There is a line in the middle of Antarctica. This is because we have split the map after reprojection. We need to fix this:
bbox1 <- st_bbox(sp_robinson)
bbox1[c(1,3)] <- c(-1e-5,1e-5)
polygon1 <- st_as_sfc(bbox1)
crosses1 <- sp_robinson %>%
st_intersects(polygon1) %>%
sapply(length) %>%
as.logical %>%
which
# Adding buffer 0
sp_robinson[crosses1, ] %<>%
st_buffer(0)
# Adding the circles to the coordinates
sp_robinson2 <- st_buffer(sp_robinson, dist = radius)
> print(sp_robinson2)
Simple feature collection with 143 features and 1 field
geometry type: POLYGON
dimension: XY
bbox: xmin: -17188220 ymin: -5706207 xmax: 17263210 ymax: 6179000
CRS: +proj=robin +lon_0=180 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs
First 10 features:
layer geometry
1 5 POLYGON ((3556791 4766657, ...
2 10 POLYGON ((13713529 4995696,...
3 10 POLYGON ((12834403 4946927,...
4 10 POLYGON ((9991443 4801974, ...
5 5 POLYGON ((4254202 4304190, ...
6 5 POLYGON ((11423719 4327354,...
7 10 POLYGON ((9582710 4282247, ...
8 10 POLYGON ((588877.2 4166512,...
9 5 POLYGON ((4522824 3894919, ...
10 10 POLYGON ((3828685 3886205, ...
sp_robinson3 <- fasterize(sp_robinson2, rs)
> print(sp_robinson3)
class : RasterLayer
dimensions : 360, 720, 259200 (nrow, ncol, ncell)
resolution : 0.5, 0.5 (x, y)
extent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
crs : +proj=robin +lon_0=180 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs
source : memory
names : layer
values : NA, NA (min, max)
I want to convert sp_robinson2 into a raster called sp_robinson3 but as you can see both fasterize()and rasterize()are giving me an empty raster layer...
The reason why rasterize does not work in the end is obvious: the crs of the vector and raster do not match. But can you edit your question a bit more to explain what you want to achieve? It is very odd to create a raster and then polygons and then rasterize these again. My impression is that you are making things much more complicated than need be. You also talk about circles. Which circles? I am guessing you may want circles around your points, but that is not what you are doing. It would probably be helpful to figure out things step by step, first figure out how to get the general result you want, then how to get it Pacific centered.
Below is a cleaned up version of the first part of your code. It also makes it reproducible. You need to create example in code, like this:
lon <- c(-177.87567, -83.2136, -82.59392, -82.4106, -81.17555, -80.9577)
lat <- c(-24.715167, 14.4018, 9.589192, 9.49275, 7.19675, 8.8527)
radius <- c(10, 1, 1, 1, 5, 1)
site <- c("MIG", "OBS", "NES", "NES;BRE", "OBS", "NES")
sp_csv_data <- data.frame(lon, lat, radius, site)
## cleaned up projection definitions
rob_pacific <- "+proj=robin +lon_0=180 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs"
longlat <- "+proj=longlat +datum=WGS84"
##Converting to raster
# Creating a empty raster at 0.5° resolution
rs <- raster(res=0.5, crs=lonlat)
values(rs) <- 1:ncell(rs)
sp_raster <- rasterize(sp_csv_data[,1:2], rs, sp_csv_data[,3])
## makes no sense: sp_raster <- resample(sp_raster, rs, resample = "ngb")
#converting into an SpatialPolygonsDataframe
species_sp <- as(sp_raster, "SpatialPolygonsDataFrame")
## makes no sense: species_sp <- spTransform(sp_raster, CRS(longlat))
I am trying to reproject some coordinates from Lambert 93 to WGS84.
I spent enought time looking for documentation and to understand better but I don't see a solution yet.
I'm looking someone that could explain me where i got wrong.
require(sp)
require(raster)
# >>>>>>>>>>>>>>>>>
# >>>>>>>>>>>>>>>>> I define the coordinates that I will use later
# >>>>>>>>>>>>>>>>>
# define coordinates ----
# Lambert 93
# epsg 2154
crs_l93 <- " +proj=lcc +lat_1=49 +lat_2=44 +lat_0=46.5 +lon_0=3
+x_0=700000+y_0=6600000 +ellps=GRS80 +units=m +no_defs"
# WGS84
# epsg 4326
crs_wgs84 <- "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"
# >>>>>>>>>>>>>>>>>
# >>>>>>>>>>>>>>>>> I define the coordinates i want to project (coord_l93)
# >>>>>>>>>>>>>>>>> and the coordinates goal (what i want them to be projected to : the result)
# >>>>>>>>>>>>>>>>> The coordinates where projected on https://epsg.io/ manually.
# >>>>>>>>>>>>>>>>>
# get data ----
# brut
coord_l93 <- data.frame("coord_x" = c(839500 , 830500 , 826500 , 826500 ) ,
"coord_y" = c(6458500, 6461500, 6467500, 6470500))
# cherché sur https://epsg.io/
coord_wgs84_hoped <- data.frame("coord_x" = c(4.7771833 , 4.6633664 , 4.6139595 , 4.6147419 ) ,
"coord_y" = c(45.2116938, 45.2404655, 45.2952272, 45.3222348))
# >>>>>>>>>>>>>>>>>
# >>>>>>>>>>>>>>>>> I set my data as SpatialPointsDataFrame and i set their projection
# >>>>>>>>>>>>>>>>>
# define new variable
sp_brut_l93 <- coord_l93
sp_brut_wgs84_hoped <- coord_wgs84_hoped
# define projection
sp::coordinates(sp_brut_l93) <- sp_brut_l93
proj4string(sp_brut_l93) <- CRS(crs_l93)
sp::coordinates(sp_brut_wgs84_hoped) <- sp_brut_wgs84_hoped
proj4string(sp_brut_wgs84_hoped) <- CRS(crs_wgs84)
# >>>>>>>>>>>>>>>>>
# >>>>>>>>>>>>>>>>> I make the projection by two different ways
# >>>>>>>>>>>>>>>>>
# project sp_coord_l93 into wgs84
sp_proj_wgs84 <- spTransform(spbv, CRS(crs_wgs84))
sp_proj_wgs84_V2 <- spTransform(spbv, "+init=epsg:4326")
# >>>>>>>>>>>>>>>>>
# >>>>>>>>>>>>>>>>> final check
# >>>>>>>>>>>>>>>>>
cat(sp_proj_wgs84)
cat(sp_brut_wgs84_hoped)
# check proj
# check that the to ways of projecting are identical
identical(coordinates(sp_proj_wgs84), coordinates(sp_proj_wgs84_V2))
# check that the projected is same as the hoped
identical(coordinates(sp_brut_wgs84_hoped), coordinates(sp_proj_wgs84))
My projection happen wrongly and i really miss the point here.
Hope anyone can explain me here.
Thank youin
Here is your code, simplified, and working
First define coordinate reference systems and data.frames with points
crs193 <- "+proj=lcc +lat_1=49 +lat_2=44 +lat_0=46.5 +lon_0=3 +x_0=700000 +y_0=6600000 +ellps=GRS80 +units=m +no_defs"
wgs84 <- "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"
xyl93 <- data.frame("coord_x" = c(839500 , 830500 , 826500 , 826500 ) ,
"coord_y" = c(6458500, 6461500, 6467500, 6470500))
xy84 <- data.frame("coord_x" = c(4.7771833 , 4.6633664 , 4.6139595 , 4.6147419 ) ,
"coord_y" = c(45.2116938, 45.2404655, 45.2952272, 45.3222348))
Create SpatialPoints by identifying the columns in the data.frame that hold the coordinates (not by assigning the coordinate reference system, although we also do that)
library(sp)
# method 1
coordinates(xyl93) <- ~ coord_x + coord_y
proj4string(xyl93) <- CRS(crs193)
# method 2
xy84 <- sp::SpatialPoints(xy84, proj4string=CRS(wgs84))
Now we can transform
x <- spTransform(xy84, crs193)
coordinates(x)
# coord_x coord_y
#[1,] 839500 6458500
#[2,] 830500 6461500
#[3,] 826500 6467500
#[4,] 826500 6470500
I'm trying to plot rainfall data from weather radar. Data file is 900x900 points matrix (900x900km). Projection informations from original cappi file:
<projection lat_lr="48.133400" lat_ul="56.186500" type="aeqd" lon_lr="25.157600" size_x="900" size_y="900" lon_ul="11.812900">
<lon_0>19.092600</lon_0>
<lat_0>52.346800</lat_0>
<ellps>+ellps=sphere</ellps>
</projection>
I'm reading data file (example: https://meteomodel.pl/examples/out.txt ) to matrix, and convert to raster:
a1 = as.matrix(read.table("/home/user/out.txt", header=F, as.is=TRUE))
a1[a1==0] <- NA
maxDBz <- 95.5
minDBz <- -31.5
step <- (maxDBz - minDBz) / 254
a1 <- minDBz + (a1 * step)
r <- raster(a1)
Then I'm trying to set extent and CRS:
e <- extent(11.812900, 25.157600, 48.133400, 56.186500)
r <- setExtent(r, e)
crs(r) <- "+proj=aeqd +lat_0=52.346800 +lon_0=19.092600 +x_0=900 +y_0=900 +ellps=sphere +datum=WGS84 +units=km +no_defs"
Data are plotted, however projection is incorrect:
https://meteomodel.pl/examples/Rplot01.png
Correct image from Polish Institute of Meteorology and Water Management:
https://meteomodel.pl/examples/cappi.png
What am I doing wrong?
What you are doing wrong is setting the extent using lon/lat crs, whereas the data have "+proj=aeqd. These need to match.
I do not know what the correct extent is, but you can approximate it like this:
p <- "+proj=aeqd +lat_0=52.346800 +lon_0=19.092600 +x_0=900 +y_0=900 +ellps=sphere +datum=WGS84 +units=km +no_defs"
e <- extent(11.812900, 25.157600, 48.133400, 56.186500)
r <- raster()
extent(r) <- e
rr <- projectExtent(r, p)
extent(rr)
#class : Extent
#xmin : -541.0182
#xmax : 452.2122
#ymin : -488.8849
#ymax : 431.1854
The txt file provided sugests that the extent you want is
e <- extent(-449997.470, 451000.522, -451003.637, 449998.274)
And that suggests that the units in your crs should be m, not km
p <- "+proj=aeqd +lat_0=52.346800 +lon_0=19.092600 +x_0=900 +y_0=900 +ellps=sphere +units=m "