I am trying to make the projection of a set of coordinates identical to a shape from wrld_simpl. But I keep getting the error below. How to solve that?
d=read.csv()
it= wrld_simpl[wrld_simpl$NAME == "Italy", ]
d=na.omit(d)
d1=d[,c("lon","lat")]
coordinates(d1)=~lon+lat
d1=spTransform(d1,CRSobj="+proj=longlat +ellps=WGS84 +towgs84=0,0,0,0,0,0,0
+no_defs")
Error in if (is.projected(obj)) { : valor ausente donde TRUE/FALSE es necesario Además: Warning message: In spTransform(xSP, CRSobj, ...) : NULL source CRS comment, falling back to PROJ string
-
here is the link to the file for a reproducible example: dropbox.com/scl/fi/wm0wok1f12ucjy3gw7ep2/…Agus camacho– Agus camacho2023年09月03日 18:39:27 +00:00Commented Sep 3, 2023 at 18:39
1 Answer 1
There's a few problems here: d1
at the error point has an NA
(missing) CRS so any attempt to reproject it with spTransform
will fail.
On my system it fails with a different error message:
> d1=spTransform(d1,CRSobj="+proj=longlat +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +no_defs")
Error in st_transform.sfc(st_geometry(x), crs, ...) :
cannot transform sfc object with missing crs
which makes me think you have an old version of sp
.
To assign a CRS to an sp
object you can use proj4string(d1) <-
like:
proj4string(d1) <- "+proj=longlat +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +no_defs"
this is telling sp
what coordinate system the numbers are. Since they look like lat-long WGS84 coordinates, I've used the proj4string you've got from the world map. At this point you should be able to plot them both with no more transformation needed:
> plot(it)
> plot(d1, add=TRUE)
If I plot the whole of the points and add the world it looks like everything lines up:
> plot(d1)
> plot(wrld_simpl, add=TRUE)
The other problem is that the sp
package is deprecated and you should look at using the sf
package and its data structures instead.
-
Thank you @spacedman! It seems I will have to stop delaying that shift to sf in my scripts.Agus camacho– Agus camacho2023年09月05日 12:18:21 +00:00Commented Sep 5, 2023 at 12:18