6

I would like to create evenly spaced polylines going North to South with 50 mile spacing between each line and 10 miles long. Not sure if this is possible using sf package. In the example below, I would like to have the lines filling the counties across the state of Washington.


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)

I've updated to include an image of what I'd like to do below.enter image description here

4

1 回答 1

3

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")

如您所见,我使用函数和来回切换sf和对象。使用这些将数据转换为您的需求。spas(sf_object, "Spatial")st_as_sf(sp_object)

在此处输入图像描述

于 2020-10-28T00:41:16.653 回答