Reputation: 1293
I have a data.frame of spatial data with crop yields by field. I want to make a heat map by rasterizing this data. I have already been able to produce a map by using raster mean values. I could improve upon this by calculating weighted averages instead, the weight being the plot area. Thus far I haven't been able to make this work.
This is what I've done as a minimal example:
require(dplyr)
require(raster)
require(sf)
d <- data.frame(longitude = runif(100, 10, 30),
latitude = runif(100, 40, 50),
yield = runif(100, 2, 6),
area = runif(100, .1, 10)) %>%
st_as_sf(coords = c("longitude", "latitude"))
r <- raster(extent(c(min(d$longitude), max(d$longitude),
min(d$latitude), max(d$latitude))))
x <- rasterize(d, r, field = "yield", mean)
In order to achieve what I need I tried e.g. replacing the last line with:
x <- rasterize(d, r, field = "yield", function(y){weighted.mean(y, w = area)})
but that does not work as I thought. Any idea how to do this?
Upvotes: 1
Views: 478
Reputation: 1854
I have modified what you did in creating a reproducible example to avoid getting error. Hope this helps:
#require(dplyr) #looks redundant
require(raster)
require(sf)
d <- data.frame(longitude = runif(100, 10, 30),
latitude = runif(100, 40, 50),
yield = runif(100, 2, 6),
area = runif(100, .1, 10)) %>%
st_as_sf(coords = c("longitude", "latitude"))
r <- raster(extent(c(st_bbox(d)))) #modified
x1 <- rasterize(d, r, field = "yield", mean)
x2 <- rasterize(d, r, field = "yield", fun=function(x,...) (sum(x[1]*x[2])/sum(x[2])))
Upvotes: 1