Search code examples
rasterr-sp

How to convert data.frame to SpatialPixelsDataFrame in R


I have a dataset tagged with latitude (y) and longitude (y).

x           y           pH      EC      RSC  SAR
644602.7184 3295635.709 7.82    1.069   6.8  2.612316328
644219.281  3293883.389 7.45    2.27    6    2.40812669
644368.6088 3295296.452 7.41    1.17    7.2  1.240347346
646050.5728 3297548.156 7.8     0.971   4.5  1.589470393
644641.7003 3295115.255 7.87    0.708   4.4  0.875069715
644764.8507 3294939.506 8       0.634   4.1  2.154375393
644885.5937 3295445.407 7.83    1.13    7.1  0.951290419

I want to convert it into SpatialPixelsDataFrame. I am using the following code:

data <- read.csv("Try_data.csv", header = T)
coordinates(data) <- ~x+y
proj4string(data) <- CRS("+proj=utm +zone=43 ellps=WGS84")

grid = spsample(data, type = "regular", cellsize = c(29.11785674, 29.11785674)) 
gridded(grid) = TRUE 
grid2 <- as(grid, "SpatialPixelsDataFrame")

But within grid2, the data.frame is coming with 0 obs. of 0 variables. I want pH, EC, RSC, SAR parameters should come in the data.frame within grid2. How to do it?


Solution

  • You seem to want to create a regular raster from irregular point data. You can either use a function like raster::rasterize, or use some type of interpolation. See e.g. raster::interpolate and the methods in the packages it uses such as gstat