I want to merge a SpatialPolygonsDataFrame
:
# From https://www.census.gov/geo/maps-data/data/cbf/cbf_state.html
states <- readOGR(dsn = "./cb_2014_us_state_20m.shp",
layer = "cb_2014_us_state_20m", verbose = FALSE)
with a normal data frame:
my_counts <- data.frame(
State = c(
"CA", "TX", "IL", "FL", "NY", "OH",
"NJ", "GA", "MI", "PA", "MA", "CO", "AZ", "NC", "VA", "WA", "IN",
"MD", "MN", "WI", "MO", "TN", "IA", "KY", "LA", "SC", "CT", "AL",
"KS", "OR", "OK", "AR", "NV", "UT", "NE", "ID", "MS", "DC", "NM",
"NH", "ME", "AK", "RI", "MT", "HI", "WV", "SD", "ND", "DE", "VT",
"WY", "PR", "GU", "VI", "MP", "AS", "na", "MH", "FM", "PW"
),
count = c(
1590533L, 1016328L, 754535L, 742603L, 714205L,
538719L, 477278L, 452064L, 437162L, 428616L, 420332L, 391084L,
380853L, 354601L, 342533L, 335505L, 294670L, 286026L, 273427L,
246172L, 238968L, 236037L, 235030L, 209514L, 199013L, 191707L,
185521L, 179931L, 163477L, 159862L, 142610L, 136006L, 120111L,
117338L, 112671L, 106176L, 102564L, 100168L, 97496L, 69881L,
69508L, 68684L, 65631L, 62109L, 61123L, 57300L, 57254L, 56091L,
51696L, 33944L, 32136L, 4822L, 598L, 468L, 49L, 19L, 17L,
11L, 2L, 1L
)
)
The goal is to use the result to make a map with leaflet
I tried sp::merge
df1 <- sp::merge(x= states, y=my_counts)
but I get an error:
Error in table(y[, by.y]) : attempt to set an attribute on NULL
stringsAsFactors=FALSE
in thereadOGR
call and in thedata.frame
creation to avoid potential factor/character issues as you manipulate the data. – Fedora