R - сделать простые функции из data.frame по идентификатору - PullRequest
0 голосов
/ 17 апреля 2020

Я попадаю в путаницу с sf в R; Я пытаюсь создать коллекцию объектов из большой системы координат данных.

Мои данные представляют собой data.frame координат x и y, и идентификатор определяет их группировку (т. Е. Один и тот же идентификатор представляет собой один многоугольник). Я хотел бы взять это и создать коллекцию sf;

# create some dummy data, coordinates for 3 squares (v. similar to provided data)
df <- data.frame(x = c(0,0,1,1,2,2,3,3,4,4,5,5), y = c(1,2,2,1,1,2,2,1,1,2,2,1), ID = rep(1:3, each = 4))

# split into a list, by ID, ready for conversion to WKT coordinate strings
split_list <- split(df, df$ID)

# the data provided does not complete the polygon, i.e. it must end with the same coordinates
# it begins with - add it in by replicating first row
split_list <- lapply(split_list, function(x) rbind(x,x[1,]))

# remove the ID column
split_list <- lapply(split_list, function(x) {x["ID"] <- NULL; x})

# create the geometry type, st_polygons (convert to matrix in the list)
o <- st_polygon(lapply(split_list,function(x) as.matrix(x)  ))

# promote to an sfc, with CRS
b_sfc <- st_sfc(o, crs = "+init=epsg:4326")

# create an data frame for the polygons
bdf <- data.frame(ID = 1:length(o), val = sample(1:1000,length(o), replace = T), row.names = NULL)

# create an sf collection of 3 polygons
pols_sf <- st_sf(bdf, geometry = b_sfc)

# on the surface it seems complete:
Simple feature collection with 3 features and 2 fields
geometry type:  POLYGON
dimension:      XY
bbox:           xmin: 0 ymin: 1 xmax: 5 ymax: 2
epsg (SRID):    4326
proj4string:    +proj=longlat +datum=WGS84 +no_defs
   ID val                       geometry
1  1 262 POLYGON ((0 1, 0 2, 1 2, 1 ...
2  2  59 POLYGON ((0 1, 0 2, 1 2, 1 ...
3  3 754 POLYGON ((0 1, 0 2, 1 2, 1 ...

# but each feature has the geometries for every polygon?
pols_sf[1,]$geometry

Geometry set for 1 feature 
geometry type:  POLYGON
dimension:      XY
bbox:           xmin: 0 ymin: 1 xmax: 5 ymax: 2
epsg (SRID):    4326
proj4string:    +proj=longlat +datum=WGS84 +no_defs
POLYGON ((0 1, 0 2, 1 2, 1 1, 0 1), (2 1, 2 2, ...

# and especially;
st_coordinates(pols_sf[1,])

   X Y L1 L2
   0 1  1  1
   0 2  1  1
   1 2  1  1
   1 1  1  1
   0 1  1  1
5  2 1  2  1
6  2 2  2  1
7  3 2  2  1
8  3 1  2  1
51 2 1  2  1
9  4 1  3  1
10 4 2  3  1
11 5 2  3  1
12 5 1  3  1
91 4 1  3  1

Как сделать так, чтобы каждая простая функция имела геометрию из 4 углов? (5 координатных пар)

1 Ответ

0 голосов
/ 22 апреля 2020

Я считаю, что необходимый результат достижим, используя комбинацию dplyr::summarize(), чтобы превратить ваши точки в многоточечные в соответствии со значением столбца идентификатора, а затем sf::st_cast() - превратить их в полигоны.

Кстати, форма ваших многоугольников выглядит не совсем правильно, и вы также можете подумать sf::st_convex_hull(), чтобы сделать их по-настоящему квадратными (если это было вашим намерением).

Я использую ваши исходные данные, только заменяя цифры c идентифицируются буквами.

library(dplyr)
library(sf)

# create some dummy data, coordinates for 3 squares (v. similar to provided data)
df <- data.frame(x = c(0,0,1,1,2,2,3,3,4,4,5,5), 
                 y = c(1,2,2,1,1,2,2,1,1,2,2,1), 
                 ID = rep(letters[1:3], each = 4),
                 stringsAsFactors = T)

# make the data frame spatial (as points)
src <- st_as_sf(df, coords = c("x", "y"))

# intermediary check
plot(src, pch = 4)

check

# from points to multipoints & finally polygons
res <- src %>%
  group_by(ID) %>%
  summarise() %>%
  st_cast("POLYGON")

# report results
plot(res)

enter image description here

...