1

I have been using merge() to merge my geojson file with csv data in R. My codes are as follows:

map@data <- merge(map@data, csvdata, by.x="ID", by.y="ID")

However, after exporting the geojson file and rendering it, the wrong numbers are always allocated to the wrong polygons.

Since the polygons were rendered properly, I guessed that there must be an error in the merge. I then tried to merge the csv data with the .shp version of the map layer on QGIS, before exporting it as geojson. This did not create any problems, which led me to the conclusion that the merging of the csv data and the map is the problem.

Is merge() incompatible with geojson file types? If so, what function from which package can I use instead?

1

I found the answers to my question here: https://stat.ethz.ch/pipermail/r-sig-geo/2008-January/003052.html

To further illustrate the answer, here's some sample data set. (I can't give a preview of my own, because it's confidential.)

CSVdata

 Area     Data   ID
Atlanta   100    1
Belgium   200    2
Canada    300    3
Denmark   400    4

Map@data (spatialpolygondataframe), geojson file

 Area       ID
Denmark     1
Canada      2
Belgium     3
Atlanta     4

I wanted to merge the two dataset, such that:

Map@data (spatialpolygondataframe), geojson file

 Area     Data   
Atlanta   100    
Belgium   200    
Canada    300    
Denmark   400    

However, I would always end up with:

 Area       Data
Denmark     100
Canada      200
Belgium     300
Atlanta     400

To test the method in the link, I first used order() my map@data. However, this did not work, as the spatialpolygondataframe consist of other dataframe, that pairs the specific polygon with the ID indicated. Using spCbind after order() would still produce the same error.

Instead, I resolved it by changing the ID tagged to the Area in my CSVdata instead. Such that:

CSVdata

 Area     Data   ID
Atlanta   100    4
Belgium   200    3
Canada    300    2
Denmark   400    1

...before conducting the spCbind.

*I have not tried it, but I believe if I use merge() now, it would still work, though spCbind would be the more appropriate and safer function.

**I tried the merge() function. It still produces the same error. I guess one should still stick strictly to spCbind for spatialpolygondataframe.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.