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?
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")