In R I am trying to aggregate points data to a grid. The data for the grid (G-Econ) comes as a csv-file. In this file each row represent a grid-cell at 1x1 degree resolution and the given coordinates, in longitude and latitude, label the south-west corner of the grid-cell.
In trying to convert these points to a grid I run into the issue that the number of grid-cells in the output (so the eventual grid-raster) does not correspond with the number of cells in the input.
Basically the short version of my question is: How do I solve this?
The simplified G-Econ csv-file can be found here and below I describe step-by-step what I've been doing.
First I load the csv-file, limit the number of observations to only include cells in African countries, and create a spatial object out of the data frame.
# Load data gecon<-read.csv("gecon.csv",header=TRUE,sep=",",row.names=NULL) gecon$Cell<-1:nrow(gecon) # Create a grid cell identifier # Limit data to African countries require(countrycode) gecon$cont<-countrycode(gecon$NEWCOUNTRYID,"iso3n","continent",warn=TRUE) g.africa<-na.omit(gecon[gecon$cont=="Africa",]) # Create spatial object require(raster) coordinates(g.africa)<-~LONGITUDE+LAT # Creates spatial object proj4string(g.africa)=CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0") summary(g.africa)
From this we see that Africa is covered by 3550 grid cells in the dataset
Next step it to transform the points into a grid:
# Transform points to grid extent<-extent(g.africa) extent # Determine number of cols. and rows for grid length(-26:63) # Number of cols: 90 length(-38:37) # Number of rows: 76 rast<-raster(extent,ncol=90,nrow=76, crs="+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0") grid<-rasterize(g.africa,rast,g.africa$Cell,fun="last") # Create grid grid
During this step the number of cells has increased -to 6840- this is due to the inclusion of cells that cover the oceans. I included a cell identifier so I can check how many of the new cells do not belong to a country.
There are 4053 NAs. Subtract these from the total number of grid-cells and the result is 2787 grid-cells, which is way less than the original number of cells for Africa. I transform the grid into polygons and this number is confirmed.
africa<-rasterToPolygons(grid) # Create spatial polygons africa # See nfeatures
So I guess something goes wrong when I rasterize the data, that somehow the interpolation of points to grid-cells results in this reduction. Due to my inexperience with GIS in R -and in general- I have been unable to solve this issue.
Does anyone have any suggestions on how I could solve this? Or maybe recommendations for a better method?