[R-sig-Geo] [Help] Error in spChFIDs(SP, x) : lengths differ
Ignacio Martinez
ignacio82 at gmail.com
Fri Sep 4 15:29:14 CEST 2015
I'm trying to create a map using leaflet. I'm basically following this
<https://github.com/rstudio/leaflet/issues/169>but my data is a bit
different this time around. Additionally, I'm using dplyr instead of
data.table.
This is the code i'm trying to run:
counts <-
structure(
list(
STUSPS = c(
"CA", "NC", "TX", "FL", "VA", "OH",
"NY", "GA", "IL", "WA", "CO", "AZ", "MD", "LA", "SC", "KS",
"DC",
"TN", "MA", "MI", "MN", "NJ", "WI", "PA", "AL", "KY", "OK",
"MO",
"ID", "MS", "NM", "IN", "NV", "AR", "OR", "AK", "UT", "IA",
"MT",
"HI", "NE", "CT", "WV", "WY", "SD", "VT", "ND", "ME", "RI",
"NH",
"DE", "PR", "GU", "VI", "MP", "AS"
), count = c(
36511L, 27513L,
25861L, 21099L, 19415L, 17012L, 15860L, 14362L, 13923L, 13753L,
11671L, 10540L, 9777L, 8923L, 8355L, 8219L, 8142L, 8076L, 7985L,
7770L, 7662L, 7531L, 7273L, 7212L, 7042L, 6708L, 6674L, 6429L,
6239L, 5580L, 5395L, 5172L, 5013L, 4933L, 4911L, 4797L, 4694L,
4458L, 3873L, 3757L, 3608L, 3111L, 2604L, 2217L, 2156L, 2143L,
2030L, 1544L, 1417L, 1168L, 772L, 531L, 148L, 63L, 7L, 2L
)
), .Names = c("STUSPS",
"count"), class = c("tbl_df", "tbl", "data.frame"),
row.names = c(NA,-56L)
)
x = c("leaflet", "rgdal", "maptools", "mapproj", "rgeos", "dplyr")
lapply(x, library, character.only = TRUE)
# From https://www.census.gov/geo/maps-data/data/cbf/cbf_state.html
states <- readOGR(dsn = "./cb_2014_us_state_5m.shp",
layer = "cb_2014_us_state_5m", verbose = FALSE)
# Make a copy of the SPDF attribute table, and then work normally, as
with any data.frame/data.table object
states.df <- states at data
# Create an explicit attribute to keep polygons IDs (useful to
"re-attach" the table to the polygons later)
states.df <- states.df %>% mutate(rn=row.names(states))
# join them
states.df <- full_join(x = states.df, y = counts, by="STUSPS") %>%
filter(!(STUSPS%in%c("PR", "na", "MH", "FM", "PW"))) %>% na.omit() %>%
mutate(popup=paste0('<b>',NAME,'</b>','<br>',
'<b>count:</b> ',
prettyNum(count,big.mark=",",scientific=FALSE)))
# Re-attach the attribute table to the SPDF
states at data <- states.df
# Make sure polygons IDs and data.frame row.names match
states <- spChFIDs(states, states$rn)
# Create map as usual...
The error I get is:
Error in spChFIDs(SP, x) : lengths differ
Thanks for the help!
Ignacio
[[alternative HTML version deleted]]
More information about the R-sig-Geo
mailing list