I have a .shp file from a grid. I read it and calculate the centroids. This data.frame has the latitude, longitude and some numbers in order making reference to the id of the grid's square. Something like that: df-centroids

With this, I try to transform it to a raster where the values are the id (like they are different numbers I think it will work), but when I plot the raster it dont use the "id" like values, and in the data of the raster object I think the "id" field has dissapeared: rasterdf1 and the image after ploting that shows this: plot(rasterdf1)

I dont know where I am wrong or where I am loosing the value field. Can anyone help me, please?

Here I leave my code:

shapeData1 <- readOGR("C:/Users/b.vcm/Documents/rural_planner_dashboard_v2",'Grid_40Km') #The .shp I use trueCentroids <- rgeos::gCentroid(shapeData1,byid=TRUE, id=shapeData1$id) df_centroids <- data.frame(trueCentroids, id = shapeData1$id) spg2 <- df_centroids coordinates(spg2) <- ~ x + y spg2 <- SpatialPixelsDataFrame(spg2, tolerance = 0.286937, spg2@data) #tolerance is because coordinate intervals are not constant due to degrees distance rasterdf1 <- raster(spg2[,'id']) plot(rasterdf1)

| improve this question | | | | |
  • I don't think you are losing it, the values in the plot are the same as values(rasterdf1) - they are mostly NA, in the raster they are non-sparse. A raster doesn't behave like a data frame, but if you had other columns in spg2 you could keep them all with brick(spg2) - and then values() on that would be a matrix, x/y down the rows, fields along the columns. – mdsumner Apr 3 '18 at 2:41

Your Answer

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

Browse other questions tagged or ask your own question.