R - 在城市地图上安装网格并将数据输入到网格方块中

2024-04-12

我试图在圣何塞上放置一个网格,如下所示:

圣何塞网格 https://i.stack.imgur.com/U8RxX.png

您可以使用以下代码直观地制作网格:

  ca_cities = tigris::places(state = "CA") #using tigris package to get shape file of all CA cities

  sj = ca_cities[ca_cities$NAME == "San Jose",] #specifying to San Jose

  UTM_ZONE = "10" #the UTM zone for San Jose, will be used to convert the proj4string of sj into UTM

  main_sj = sj@polygons[[1]]@Polygons[[5]] #the portion of the shape file I focus on. This is the boundary of san jose

  #converting the main_sj polygon into a spatialpolygondataframe using the sp package
  tst_ps = sp::Polygons(list(main_sj), 1)
  tst_sps = sp::SpatialPolygons(list(tst_ps))
  proj4string(tst_sps) = proj4string(sj)
  df = data.frame(f = 99.9)
  tst_spdf = sp::SpatialPolygonsDataFrame(tst_sps, data = df)

  #transforming the proj4string and declaring the finished map as "map"
  map = sp::spTransform(tst_sps, CRS(paste0("+proj=utm +zone=",UTM_ZONE," ellps=WGS84")))

  #designates the number of horizontal and vertical lines of the grid
  NUM_LINES_VERT = 25
  NUM_LINES_HORZ = 25
  #getting bounding box of map
  bbox = map@bbox
  #Marking the x and y coordinates for each of the grid lines.
  x_spots = seq(bbox[1,1], bbox[1,2], length.out = NUM_LINES_HORZ)
  y_spots = seq(bbox[2,1], bbox[2,2], length.out = NUM_LINES_VERT)

  #creating the coordinates for the lines. top and bottom connect to each other. left and right connect to each other
  top_vert_line_coords = expand.grid(x = x_spots, y = y_spots[1])
  bottom_vert_line_coords = expand.grid(x = x_spots, y = y_spots[length(y_spots)])
  left_horz_line_coords = expand.grid(x = x_spots[1], y = y_spots)
  right_horz_line_coords = expand.grid(x = x_spots[length(x_spots)], y = y_spots)

  #creating vertical lines and adding them all to a list
  vert_line_list = list()
  for(n in 1 : nrow(top_vert_line_coords)){
    vert_line_list[[n]] = sp::Line(rbind(top_vert_line_coords[n,], bottom_vert_line_coords[n,]))
  }

  vert_lines = sp::Lines(vert_line_list, ID = "vert") #creating Lines object of the vertical lines

  #creating horizontal lines and adding them all to a list
  horz_line_list = list()
  for(n in 1 : nrow(top_vert_line_coords)){
    horz_line_list[[n]] = sp::Line(rbind(left_horz_line_coords[n,], right_horz_line_coords[n,]))
  }

  horz_lines = sp::Lines(horz_line_list, ID = "horz") #creating Lines object of the horizontal lines

  all_lines = sp::Lines(c(horz_line_list, vert_line_list), ID = 1) #combining horizontal and vertical lines into a single grid format

  grid_lines = sp::SpatialLines(list(all_lines)) #converting the lines object into a Spatial Lines object
  proj4string(grid_lines) = proj4string(map) #ensuring the projections are the same between the map and the grid lines.

  trimmed_grid = intersect(grid_lines, map) #grid that shapes to the san jose map

  plot(map) #plotting the map of San Jose
  lines(trimmed_grid) #plotting the grid

然而,我正在努力将每个网格“正方形”(一些网格块不是正方形,因为它们适合圣何塞地图的形状)变成一个我可以输入数据的容器。换句话说,如果每个网格“方块”的编号为 1:n,那么我可以创建一个如下所示的数据框:

  grid_id num_assaults num_thefts
1       1          100         89
2       2           55        456
3       3           12       1321
4       4           48        498
5       5           66          6

并用每次犯罪发生的点位置的数据填充每个网格“方块”,希望使用over()函数从sp包裹。

我已经尝试解决这个问题好几个星期了,但我无法弄清楚。我一直在寻找一个简单的解决方案,但我似乎找不到。任何帮助,将不胜感激。


此外,这是一个基于 sf 和 tidyverse 的解决方案:

使用 sf,您可以使用以下命令制作一个正方形网格st_make_grid()功能。在这里,我将在圣何塞的边界框上创建一个 2 公里长的网格,然后将其与圣何塞的边界相交。请注意,我正在投影到 UTM 区域 10N,因此我可以指定以米为单位的网格大小。

library(tigris)
library(tidyverse)
library(sf)
options(tigris_class = "sf", tigris_use_cache = TRUE)
set.seed(1234)

sj <- places("CA", cb = TRUE) %>%
  filter(NAME == "San Jose") %>%
  st_transform(26910)

g <- sj %>%
  st_make_grid(cellsize = 2000) %>%
  st_intersection(sj) %>%
  st_cast("MULTIPOLYGON") %>%
  st_sf() %>%
  mutate(id = row_number())

接下来,我们可以生成一些随机犯罪数据st_sample()并绘制它来看看我们正在处理什么。

thefts <- st_sample(sj, size = 500) %>%
  st_sf()

assaults <- st_sample(sj, size = 200) %>%
  st_sf()

plot(g$geometry)
plot(thefts, add = TRUE, col = "red")

然后可以将犯罪数据连接到空间网格中st_join()。我们可以绘图来检查我们的结果。

theft_grid <- g %>%
  st_join(thefts) %>%
  group_by(id) %>%
  summarize(num_thefts = n())

plot(theft_grid["num_thefts"])

然后我们可以对攻击数据执行相同的操作,然后将两个数据集连接在一起以获得所需的结果。如果您有大量犯罪数据集,可以修改这些数据集以使其在某些变化范围内工作purrr::map().

assault_grid <- g %>%
  st_join(assaults) %>%
  group_by(id) %>%
  summarize(num_assaults = n()) 

st_geometry(assault_grid) <- NULL

crime_data <- left_join(theft_grid, assault_grid, by = "id")

crime_data

Simple feature collection with 190 features and 3 fields
geometry type:  GEOMETRY
dimension:      XY
bbox:           xmin: 584412 ymin: 4109499 xmax: 625213.2 ymax: 4147443
epsg (SRID):    26910
proj4string:    +proj=utm +zone=10 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs
# A tibble: 190 x 4
      id num_thefts num_assaults                                                     geometry
   <int>      <int>        <int>                                               <GEOMETRY [m]>
 1     1          2            1 POLYGON ((607150.3 4111499, 608412 4111499, 608412 4109738,…
 2     2          4            1 POLYGON ((608412 4109738, 608412 4111499, 609237.8 4111499,…
 3     3          3            1 POLYGON ((608412 4113454, 608412 4111499, 607150.3 4111499,…
 4     4          2            2 POLYGON ((609237.8 4111499, 608412 4111499, 608412 4113454,…
 5     5          1            1 MULTIPOLYGON (((610412 4112522, 610412 4112804, 610597 4112…
 6     6          1            1 POLYGON ((616205.4 4113499, 616412 4113499, 616412 4113309,…
 7     7          1            1 MULTIPOLYGON (((617467.1 4113499, 618107.9 4113499, 617697.…
 8     8          2            1 POLYGON ((605206.8 4115499, 606412 4115499, 606412 4114617,…
 9     9          5            1 POLYGON ((606412 4114617, 606412 4115499, 608078.2 4115499,…
10    10          1            1 POLYGON ((609242.7 4115499, 610412 4115499, 610412 4113499,…
# ... with 180 more rows
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

R - 在城市地图上安装网格并将数据输入到网格方块中 的相关文章

随机推荐

  • 使用 intelliJ 将字符串串联重构为 StringBuilder

    我被指定对一个项目进行重构 我遇到了这种情况 this path DESTINY deploy name FILE SEPARATOR delivery getSystem getCode FILE SEPARATOR delivery g
  • 求 a^b^c^... mod m

    我想计算一下 abcd mod m 你知道有什么有效的方法吗 因为这个数字太大了 但 a b c 和 m 适合一个简单的 32 位 int 有任何想法吗 Caveat This question is different from find
  • Spring 5 的反应式 WebSockets - 如何获取初始消息

    我遵循了该教程 特别是浏览器 WebSocket 客户端的部分 http www baeldung com spring 5 reactive websockets http www baeldung com spring 5 reacti
  • ASP.NET MVC4 实体验证错误:用户名已被占用

    我是 ASP NET MVC4 的新手 在下面的代码中遇到验证错误 我的应用程序正在使用身份和数据库 我有一些表填充了一些测试数据 致电dc SaveChanges 返回验证错误 我创建了以下类 Faculty源自类Person源自类Ide
  • 如何通过 Pktgen-DPDK 生成随机流量?

    I use range
  • 将 TStringList 的 AddObject 与整数一起使用?

    使用德尔福7 如何将整数添加到字符串列表项的目标部分 使用AddObject 如何从对象中检索整数 字符串列表项的属性 如何释放所有对象并列出 什么时候完成 Q How can i add an integer to the object
  • 将过滤器应用于 AS3 中的所有内容

    我正在尝试在 AS3 Flex SDK 中添加过滤器 我可以为任何一个对象添加一个过滤器 但我想将过滤器应用到一切那是某个对象的子对象 假设弹出一个暂停窗口 暂停窗口下方的所有内容都会变得模糊 将过滤器应用于每个单独的对象 例如 迭代列表
  • 如何更改 GTK 中的字体大小?

    有没有一种简单的方法可以更改 GTK 中文本元素的字体大小 现在我能做的就是set markup在标签上 写着一些愚蠢的东西 比如 lbl set markup span s span text 这 1 需要我设置字体 2 似乎有很多开销
  • wpf - 如何控制用户控件鼠标悬停的可见性?

    我有一个用户控件 我想禁用 UserControl 中控件的可见性 我只希望当用户的光标悬停在用户控件的主要部分 即 橙色 矩形部分 上时它可见 红色圆圈是控件的一部分 仅在 悬停 时可见 主窗口 xaml
  • 如何在没有文本框的情况下在 Selenium 中上传文件

    我一直在寻找在 Selenium 2 中上传文件的解决方案 问题是我尝试上传的网络元素可以通过两种方式使用 拖放或单击按钮 没有字段输入框 并不是说我没有尝试过使用 sendKeys 我已经在按钮和所有周围的元素上尝试过 这个问题的第二部分
  • DocFx:如何在网站上创建目录导航?

    我想创建一个目录 看起来像什么DocFx 在他们的官方网站上有 http dotnet github io docfx tutorial docfx exe user manual html 使用默认值docfx init使用所有默认值的命
  • Python wilcoxon:不等N

    Rs wilcox test可以采用不同长度的向量 但 wilcoxon 来自scipy stats不能 我得到一个unequal N错误信息 from scipy stats import wilcoxon wilcoxon range
  • 从 GPS 坐标获取城市名称

    我想从 GPS 坐标获取城市的名称 我可以使用 Google API 获取 GPS 点的详细信息 http maps googleapis com maps api geocode output parameters 输出是 XML 但我不
  • 如何导出带有产品完整 url 的产品 csv

    我想导出包含完整产品 url 的产品 CSV 即包括基本 url 我不想手动执行此操作 是否可以自定义代码 以便产品导出具有完整的 url
  • 如何读取在 gradle 执行中较早更新的属性文件中的最新属性

    对于我的 Android 项目 我配置了 defaultConfig 以便它从 gradle properties 中的版本属性获取生成的 apk 中 AndroidManifest xml 的 versionName 这很好用 这是 bu
  • 谷歌图片搜索是如何实现的?

    我只需拖放谷歌中的任何图像即可获得结果 它是如何实施的 该算法背后的想法是什么 该图像数据是否转换为任何内容以供搜索或 不知道 令人惊讶的是 我们还可以使用Google来回答这个问题 Google 按图像搜索使用的算法是什么 http ww
  • 在 ghci 中跟踪历史

    历史管理在 GHCI 或其他基于 Haskell 的 REPL 中如何工作 由于 Haskell 是一种纯语言 我猜它是使用 monad 实现的 也许是状态单子 http learnyouahaskell com for a few mon
  • 使用 apt-get install nginx 后重新编译 nginx

    我最初是通过 apt get install 安装 nginx 的 它工作得很好 现在 我想安装一些第 3 方模块 并且必须重新编译 nginx 所以我尝试重新编译 它只是走过场 然后我意识到我的原始版本仍然是正在使用的版本 我是否需要先卸
  • Python ImportError:无法在 virtualenv 中导入名称“_imagingtk”

    我想开始使用枕头 但遇到了一些问题 起初 我以为我可以简单地pip install pillow 所以我激活了我的 virtualenv 并做到了这一点 当它不起作用时 我意识到我需要为枕头安装一些依赖项 安装 http pillow re
  • R - 在城市地图上安装网格并将数据输入到网格方块中

    我试图在圣何塞上放置一个网格 如下所示 圣何塞网格 https i stack imgur com U8RxX png 您可以使用以下代码直观地制作网格 ca cities tigris places state CA using tigr