Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You are breaking the sp (shapefile) object in multiple ways. You cannot not add data to the dbf independently of the operating on the shapefile. Everything is indexed in one of the binary files (shx) comprising the shapefile. You are also breaking the internal relationship of the sp object by using merge. </p> <p>The most efficient way is to use rgdal to read the shapefile, join the dbf, and finally write out (or overwrite) a new shapefile.</p> <pre><code>require(rgdal) require(sp) require(foreign) # Read data shp &lt;- readORG(getwd(), "ShpName") tbl &lt;- read.dbf("infile.dbf") # Merge data using match shp@data = data.frame(shp@data, tbl[match(shp@data[,"GEO_ID"], tbl[,"GEO_ID"]),]) # Write new shapefile with added attributes, THe additional flags will overwrite if # the name is the same as the original writeOGR(shp, getwd(), "NewShp", driver="ESRI Shapefile", check_exists=TRUE, overwrite_layer=TRUE) </code></pre> <p>If you need a more formal merge function you can use this.</p> <pre><code>########################################################################## # PROGRAM: merge.sp.df # # USE: JOINS A dataframe OBJECT TO A sp CLASS SpatialDataFrame OBJECT # KEEPING INTEGRITY OF DATA # # REQUIRES: sp CLASS SpatialDataFrame OBJECT # PACKAGES: sp # # ARGUMENTS: # x sp SpatialDataFrame OBJECT # y dataframe OBJECT TO MERGE # xcol MERGE COLUMN NAME IN sp OBJECT # ycol MERGE COLUMN NAME IN dataframe OBJECT # # EXAMPLE: # # Not Run (dat.sp is sp object and dat is a data.frame to merge # dat.sp &lt;- merge.sp.df(dat.sp, dat, "dat.sp-ID", "dat-ID") # # VALUE: # A NEW SpatialDataFrame OBJECT WITH MERGED DATA ########################################################################## merge.sp.df &lt;- function(x, y, xcol, ycol) { x@data$sort &lt;- 1:nrow(as(x@data, "data.frame")) xdf &lt;- as( x@data, "data.frame") xdf &lt;- merge(xdf, y, by.x=xcol, by.y=ycol) xdf &lt;- xdf[order(xdf$sort), ] row.names(xdf) &lt;- xdf$sort xdf &lt;- xdf[,- which(names(xdf) == "sort")] x@data &lt;- xdf return(x) } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload