Eduardo Bongiolo
Eduardo Bongiolo

Reputation: 123

Set coordinate reference system to a polygon created in R

I am trying to create a zoom-in square(polygon) in a map that is plot using ggplot2::geom_sf() Therefore, I need the polygon to be a simple feature so I can plot the square and the map together. I could create the polygon using the following code.

zoom_square_1<- rbind(c(-10.821079,-68.403542),
                  c(-10.821079,-68.367060),
                  c(-10.862918,-68.367060),
                  c(-10.862918,-68.403542),
                  c(-10.821079,-68.403542)) # add the first point again to it wrap up.
zoom_square_1_pol <- st_polygon(list(zoom_square_1))
plot(zoom_square_1_pol) # it returns the polygon.

However, when I tried to assign a Coordinate reference system (CRS) to it, it does not work. These are the codes I have tried so far.

sp::proj4string(zoom_square_1_pol) <- CRS("+proj=longlat +datum=WGS84 +no_defs")
zoom_square_1_pol_ex1 <- st_as_sf(x = zoom_square_1_pol[[1]],
                              crs = "+proj=longlat +datum=WGS84 +no_defs")
zoom_square_1_pol_ex2 <- st_transform(x = zoom_square_1_pol,
                                  crs = "+proj=longlat +datum=WGS84 +no_defs")

Any help is welcomed.

After Chris comment, I could actually plot the polygons using ggplot2::geom_sf() and realized that my lat and long coordenates were in the wrong position since the begging. So, this the is final version of the code:

 zoom_square_1<- rbind(c(-68.403542,-10.821079),
                       c(-68.367060,-10.821079),
                       c(-68.367060,-10.862918),
                       c(-68.403542,-10.862918),
                       c(-68.403542,-10.821079)) #add the first point again to it wrap up.
zoom_square_1_pol <- st_polygon(list(zoom_square_1))
zoom_square_1_pol_CRS<- st_sfc(x = zoom_square_1_pol,
                               crs = "+proj=longlat +datum=WGS84 +no_defs")

Upvotes: 3

Views: 559

Answers (1)

jsta
jsta

Reputation: 3393

I was able to set the crs by feeding the square as a list to st_as_sfc:

res <- st_as_sfc(list(zoom_square_1_pol), 
                 crs = "+proj=longlat +datum=WGS84 +no_defs")

Upvotes: 2

Related Questions