Reputation: 95
I am working on creating a custom US map in R. I want to alter one state's geometry to fit how I need it. As a base, I am using the FiveThirtyEight electoral map from the tilegramsR
package. Below is the code I use to get all of the states.
library(tilegramsR)
library(dplyr)
States <- sf_FiveThirtyEightElectoralCollege.states
This gives a data frame where the first column is a state and the second is the geometry of the border (it comes out to looking like a bunch of connected hexagons for each state).
I want to replace one of the states' geometry. I already have coordinates, however, it is currently stored in a data frame. The exact coordinates are long, but structure of the data is listed below.
exCoords <- data.frame(V1 = c(1,1,2,2,1),
V2 = c(1,2,2,1,1))
The first row is the first set of coordinates, the second is the second (Coordinate 1 (x,y) = exCoords[1, 1], exCoords[1, 2], Coordinate 2 (x,y) = exCoords[2, 1], exCoords[2, 2]) etc. . .
What I want to do is convert the data frame coordinates to a geometry object like in the States frame I am using, and replace one of the states coordinates with the ones I have created. How would I go about that with the new coordinates currently stored as a data frame?
Upvotes: 1
Views: 372
Reputation: 18425
Each element of the geometry
column is simply a two-column matrix wrapped in a list in another list. You can therefore just edit them directly...
States$geometry[n][[1]][[1]] <- as.matrix(exCoords)
where n
is the row number of States
that you want to replace. All of the sfc_geometry attributes are retained.
Upvotes: 2