使用R在县上创建等距的折线

问题描述

我想创建从北到南平均间隔的折线,每条线之间的距离为50英里,长度为10英里。不知道是否可以使用sf包。在下面的示例中,我希望线段充满华盛顿州的各个县。


library(tigris)
library(leaflet)

states <- states(cb = TRUE)

counties<-counties(cb=TRUE)

counties<- counties%>%filter(STATEFP==53)

states<- states%>%filter(NAME=="Washington")

leaflet(states) %>%
  addProviderTiles("CartoDB.Positron") %>%
  addpolygons(fillColor = "white",color = "black",weight = 0.5) %>%
  addpolygons(data=counties,color='red',fillColor = 'white')%>%
  setView(-120.5,47.3,zoom=8)

我已更新为在下面添加一张我想做的图片

enter image description here

解决方法

您可以通过指定坐标从头创建multilinestring sf对象。

您可以从华盛顿的extent(边界框)获得这些坐标,但是您可能还想知道如何创建网格,下面将对其进行演示,因为它可能会有所帮助。

复制并粘贴此可复制示例:

library(tidyverse)
library(tigris)
library(leaflet)
library(sf)
library(raster)

states <- states(cb = TRUE)

# subset for WA and transform to a meter-based CRS 
states <- states %>% 
  filter(NAME == "Washington") %>% 
  st_transform(crs = 3857) # Mercator

# fifty miles in meters
fm <- 80467.2

# subset for Washington
states_sp <- as(states,"Spatial")

# create a grid,convert it to polygons to plot
grid <- raster(extent(states_sp),resolution = c(fm,fm),crs = proj4string(states_sp))
grid <- rasterToPolygons(grid)
plot(states_sp)
plot(grid,add = TRUE)

# find the top y coordinate and calculate 50 mile intervals moving south
ty <- extent(grid)[4]  # y coordinate along northern WA edge
ty <- ty - (fm * 0:7)  # y coordinates moving south at 10 mile intervals

# create a list of sf linestring objects
l <- vector("list",length(ty))
for(i in seq_along(l)){
  l[[i]]  <- 
    st_linestring(
      rbind(
        c(extent(grid)[1],ty[i]),c(extent(grid)[2],ty[i])
      )
    )
}

# create the multilinestring,which expects a list of linestrings
ml <- st_multilinestring(l) 

plot(states_sp)
plot(as(ml,"Spatial"),add = TRUE,col = "red")

如您所见,我使用功能sfspas(sf_object,"Spatial")st_as_sf(sp_object)对象之间来回切换。使用这些将数据转换为您的需求。

enter image description here