R - recenter SpatialPolygonsDataFrame from Atlantic to Pacific view but keep data

Viewed 118

I need to overlay a western hemisphere SpatialPolygonsDataFrame of Peru, with longitude (-81.3307,-68.65311) on a large RasterBrick of climate data (dim = 721 1440 14610) with longitude (-0.125,359.875). Of course this is not possible because the shapefile is on Atlantic view, the rasterbrick on Pacific view.

I first tried using rotate() to recenter the rasterbrick on atlantic view, but this is impossibly time-consuming.

I then found recenter() from the sp package. This works; the new Peru shapefile is in Pacific view. However, it's a SpatialPolygons only -- it looses the data I had in the SpatialPolygonsDataFrame of Peru. Is there any way to keep the data, or does another, similar function keep the data?

2 Answers

If you want to stay in sp and use recenter(), I think the only way to do that would be to copy the data.frame back to the output SpatialPolygons. Something like:

peru_pac <- recenter(peru_atl)
peru_pac_spdf <- SpatialPointsDataFrame(peru_pac, peru_atl@data)

But I would also recommend using the newer sf package instead whenever possible. If you already have a SpatialPolygonsDataFrame object, it's easy to convert to a simple features object with sfobject <- st_as_sf(spdataframe), and then use st_shift_longitude. If you need to convert back to sp objects, you can do so with spdataframe <- as(sfobject, "Spatial").

Related