I wanted to join a CSV file to a shapefile.
When I identified a field to facilitate the join, e.g.,
map <- spChFIDs(map, as.character(map$ID))
Error in spChFIDs(SP, x) : lengths differ
Can anyone advise?
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It only takes a minute to sign up.Sign up to join this community
Here is how you can do it in R using
library(raster) # read data p <- shapefile("path/file.shp") d <- read.csv("path/file.csv") # merge on common variable, here called 'key' m <- merge(p, d, by='key') # perhaps save as shapefile again shapefile(m, "path/merged.shp")
I don't know how to do with R to join a shapefile with a csv. However, if this can help you, you can also do this on QGIS using the pluggin MMQGIS.
If you're working in R then your shapefile and .csv need to be loaded as a data.frame or a data.table. You can use join() to merge them.
Do you have any more information about what kind of shapefile you have?
I've had luck doing the following when I merge shapefiles and data. Note that you need to leave off the .shp extension in the "layer" argument. I used "GEOID" where you'd put whatever the name of the "shape" in interest is.
library("rgdal") library("data.table") shapefile = readOGR(dsn = "DIRECTORY WITH SHAPEFILES", layer = "THE ACTUAL SHAPEFILE") shapefile@data$id = rownames(shapefile@data) shapefile.points = fortify(shapefile, region = "id") shapefile.df = join(shapefile.points, shapefile@data, by = "id") shapefile.df = subset(shapefile.df, select = c(long, lat, group, GEOID)) names(shapefile.df) = c("long", "lat", "group", "GEOID")
Then you can merge your data using something like
full.data = join(mydata, shapefile.df, by = "GEOID", type = "full")
If you are working in R then merging is actually not required. You can use ggplot to display your data on a map. See, my example. This one liner works wonders with shape file
bangladesh = fortify(p1, region = "ADM1_EN"). And, then you can use
ggplot() + geom_map(data = br2016a, aes(map_id = ADM1_EN, fill = HectareLocal), map =bangladesh) + expand_limits(x = bangladesh$long, y = bangladesh$lat) + coord_fixed(.96) + scale_fill_gradient(low="thistle2", high="darkred", guide="colorbar", na.value="white") + labs(title = "Bangladesh Boro Rice (Local variety), 2016", x = element_blank(), y = element_blank(), fill='Hectares') + theme(legend.position = "bottom")
And, the map I get is here.