4

Basically, I am trying to convert an sf object into a raster file, to be plotted with leaflet. the sf object look like this:

Simple feature collection with 33901 features and 1 field
geometry type:  POINT
dimension:      XY
bbox:           xmin: 63.42624931 ymin: -18.21972306 xmax: 175.2237467 ymax: 58.60000076
geographic CRS: WGS 84
First 10 features:
     df$prhmax                       geometry
1  24.46245324 POINT (77.57315415 -17.2288...
2  24.48866948 POINT (77.97969243 -17.1712...
3  24.51029786 POINT (78.38618742 -17.1142...
4  24.51992770 POINT (78.79264389 -17.0577...
5  24.52394288 POINT (79.199056 -17.00185241)
6  24.53245239 POINT (79.60542849 -16.9464...
7  24.56160049 POINT (80.01176604 -16.8915...
8  24.60146712 POINT (80.41806278 -16.8372...
9  24.62994385 POINT (80.82432335 -16.783531)
10 24.65465755 POINT (81.23055239 -16.7303...

I have been struggling to solve this. If I just do plot(sf.object) it works fine, but I am not able to make a raster.

IvanSanchez
  • 18,272
  • 3
  • 30
  • 45
Riccardo
  • 41
  • 1
  • 2

1 Answers1

4

Generate a raster layer and rasterize the points to it.

# Load packages
packs <- list("tidyverse", "raster", "sf")
lapply(packs, require, character.only = T)

# Convert points to sp (assumes that the sf object is called example_points)
example_points <- as(example_points, "Spatial")

# Generate empty raster layer and rasterize points
example_raster <- raster(crs = crs(example_points), vals = 0, resolution = c(0.5, 0.5), ext = extent(c(-180, 180, -90, 90))) %>%
   rasterize(example_points, .)

Given that the points are longlat projected, the code generates a global raster layer of a 30 x 30 arc minute resolution with cell values set to zero. rasterize then converts the points to a raster layer based on the example raster layer. You might want to set the rasterize function's field and fun arguments which control how the points determine the cell values. With the former you can control which variable sets the cell values. The latter defines the function calculating the cell values - e.g. counting the points that intersect with the pixel or calculating the mean of all intersecting points' values.

Chr
  • 1,017
  • 1
  • 8
  • 29