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.
Best Answer
The most robust way to do this, is to use GDAL's ogr2ogr functionality. Since you know your datatypes, you can specify them in
VRT
file.The documentation has this to say about setting field types:
So if your CSV data is like this:
You should build a VRT like this:
Now you can export to GeoJSON with the following command:
ogr2ogr -f GeoJSON output.geojson data.vrt