以下是可重复使用的数据:
structure(list(countyfp10 = c(1, 1, 1, 1, 3, 3, 3, 3, 5, 5, 5,
5, 7, 7, 7, 7), id = c(7417, 7418, 7419, 7420, 7421, 7422, 7423,
7424, 7425, 7426, 7427, 7428, 7429, 7430, 7431, 7432), lat = c(39.4797245,
39.5544678, 39.4681687, 39.199806, 39.4017623, 39.3093943, 39.4272021,
39.5618129, 39.7934997, 39.4835134, 39.4989196, 39.4819145, 39.4727694,
39.4675515, 39.4693146, 39.4644503), long = c(-118.7908571, -118.8095638,
-118.8195712, -118.5429041, -118.754186, -118.8861865, -118.9729817,
-117.9418517, -118.9516281, -118.8487913, -119.0205114, -118.7695846,
-118.7938896, -118.76011, -118.7778707, -118.7902103)), class = c("spec_tbl_df",
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -16L), spec = structure(list(
cols = list(countyfp10 = structure(list(), class = c("collector_double",
"collector")), id = structure(list(), class = c("collector_double",
"collector")), lat = structure(list(), class = c("collector_double",
"collector")), long = structure(list(), class = c("collector_double",
"collector"))), default = structure(list(), class = c("collector_guess",
"collector")), skip = 1), class = "col_spec"))
当前存储为data.frame
,但我想将其转换为SpatialPolygonsDataFrame
。最好的方法是什么?
答案 0 :(得分:2)
为此我一直在开发sfheaders
库。它尚未在CRAN上,但已经接近(如果您对使用库的开发版本感到满意)
devtools::install_github("dcooley/sfheaders")
library(sfheaders)
sf <- sfheaders::sf_polygon(
obj = df
, x = "long"
, y = "lat"
, polygon_id = "countyfp10"
)
并显示它可以在传单中使用(其他plotting libraries也可用;))
library(leaflet)
leaflet() %>%
addTiles() %>%
addPolygons(data = sf)
答案 1 :(得分:1)
如评论中所述,sf是最方便使用的软件包,这是一个示例。
请注意,数据集已修改为形成封闭的多边形,如果我们将其与原始数据一起尝试,则会引发错误。
data = tibble(countyfp10 = c(1, 1, 1, 1,1, 3, 3, 3, 3,3, 5, 5, 5,5,
5, 7, 7, 7, 7,7), id = c(7413,7414,7415,7416,7417, 7418, 7419, 7420, 7421, 7422, 7423,
7424, 7425, 7426, 7427, 7428, 7429, 7430, 7431, 7432), lat = c(39.4797245,
39.5544678, 39.4681687, 39.199806,39.4797245, 39.4017623, 39.3093943, 39.4272021,
39.5618129,39.4017623, 39.7934997, 39.4835134, 39.4989196, 39.4819145,39.7934997, 39.4727694,
39.4675515, 39.4693146, 39.4644503,39.4727694), lng = c(-118.7908571, -118.8095638,
-118.8195712, -118.5429041,-118.7908571, -118.754186, -118.8861865, -118.9729817,
-117.9418517,-118.754186, -118.9516281, -118.8487913, -119.0205114, -118.7695846,-118.9516281,
-118.7938896, -118.76011, -118.7778707, -118.7902103,-118.7938896))
cords = data%>%
select(countyfp10,lng,lat)%>%
mutate(lng = as.numeric(lng),
lat = as.numeric(lat))%>%
group_by(countyfp10)%>%
summarise(coordinates = list(list(matrix(c(lng,lat),ncol = 2)))) %>%
.$coordinates %>%
lapply(.,st_polygon) %>%
st_sfc(.)
cords %>%
leaflet() %>%
addTiles()%>%
addPolygons()