0

I have

library(world) 
library(ggplot)
library(sf)

world_coords<-map_data("world")
afghan<-world_coordinates[which(world_coordinates$region=="Afghanistan"),]
afghanshape<-st_polygon(list(cbind(afghan$long,afghan$lat)))
grid_spacing<-st_area(afghanshape)/100
 gridy<- st_make_grid(afghanshape,square=T,cellsize = c(grid_spacing,grid_spacing))%>%st_sf()
  inners<-as.matrix(st_contains(afghanshape,gridy))
  indices_inners<-which(inners==TRUE)

which gives the outputs

plot(afghanshape)

enter image description here


plot(gridy[indices_inners,],add=T)

enter image description here

and I'd like to be able to call on each row in the grid in order to get its bounding box using st_bbox so that I may then integrate over these rectangular regions as an approximation for the area of the area of Afghanistan.

How do I do this?

1 Answer 1

1

You can use centroid data for this purpose:

gridy=gridy[indices_inners,]

centroids<-st_coordinates(st_centroid(gridy))
centroids <- round(centroids,3)
unique_y<-unique(centroids[,2])


colors_<-sample(colors(),length(unique_y))

plot(gridy,col=NA, border=NA)
for (i in 1:length(unique_y)){
  plot(gridy[centroids[,2] %in% unique_y[i],],col=colors_[i],add=TRUE)
}

I rounded the centroid y coordinate in order to avoid issues by approximation

enter image description here

Then you can use gridy[centroids[,2] %in% unique_y[nrow],] for selecting the row from bottom to top.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.