Поведение st_make_grid () из пакета R sf - PullRequest
0 голосов
/ 04 августа 2020

Я пытаюсь создать регулярную сетку в шейп-файлах страны, используя следующий код.

library(tidyverse)
library(sf)
#> Linking to GEOS 3.8.0, GDAL 3.0.4, PROJ 6.3.1
library(rnaturalearth)

# Select 2 countries
countries <- ne_countries(returnclass = "sf") %>% 
  filter(iso_a2 %in% c("DK", "SE"))

countries %>% 
  ggplot() +
  geom_sf(aes(fill = iso_a2))

Create a grid of 50x50

countries_grid <- countries %>% 
  st_make_grid(n = 50) 
#> although coordinates are longitude/latitude, st_relate_pattern assumes that they are planar

countries_grid
#> Geometry set for 1069 features 
#> geometry type:  POLYGON
#> dimension:      XY
#> bbox:           xmin: 8.089977 ymin: 54.80001 xmax: 23.90338 ymax: 69.10625
#> CRS:            +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
#> First 5 geometries:
#> POLYGON ((8.406245 54.80001, 8.722513 54.80001,...
#> POLYGON ((8.722513 54.80001, 9.038781 54.80001,...
#> POLYGON ((9.038781 54.80001, 9.355049 54.80001,...
#> POLYGON ((9.355049 54.80001, 9.671317 54.80001,...
#> POLYGON ((9.671317 54.80001, 9.987585 54.80001,...

countries_grid %>% 
  ggplot() +
  geom_sf()

So far it works. The problem I am facing is that I am losing the variable that indicates the countries. Hence, I can not use the fill argument.

countries_grid %>% 
  ggplot() +
  geom_sf(aes(fill = iso_a2))
#> Error in FUN(X[[i]], ...): object 'iso_a2' not found

Есть ли способ добавить информацию о стране в сетку, созданную с помощью st_make_grid()?

EDIT:

Я нашел решение, используя st_as_sf() и st_join().

countries_grid %>%
  st_as_sf() %>% 
  st_join(countries) %>% 
  ggplot() +
  geom_sf(aes(fill = iso_a2))
#> although coordinates are longitude/latitude, st_intersects assumes that they are planar

Created on 2020-08-04 by the пакет REPEX (v0.3.0.9001)

...