0

I´m pretty new in R so I hope you guys can help me with this step, since I´m pretty stuck.

I have a table with monitoring points (coordinates) and a water quality index for each of them. I´m trying to create a raster from this table with the rasterize function:

rasterize(x, raster, field, fun=mean, backgroud=0, update=TRUE)

x= dataframe with coordinates

raster= created with the extent, nrows, ncols and more from a reference raster.

field= a vector created with the water quality index data. Each value belong to a one point from the x table.

fun=mean= I need the mean of all the point that are in the same cell.

background=0 to complete the cell that has no value derived from field.

update=TRUE so the values in the cells got update with the vector values

After running this I got a map with the rigth extension but with no data (all blank) and the next summary (sometimes I got NA´s or 2´s instead of 5´s, no idea why):

Min.            5
1st Qu.         5
Median          5
3rd Qu.         5
Max.            5
NA's    215695154

I think the problen is with the function, but I´m not sure. I tried to change the function as follows, but I have the same result.

na.rm=mean(na.omit(v))
raster.wq=rasterize(xy, raster, v, fun=function(v,na.rm)mean(v), backgroud=0, update=TRUE)

Thank you very much in advance. Cheers.

SayAz
  • 751
  • 1
  • 9
  • 16

1 Answers1

1

Next time includes a minimal reproducible exampe. However, you have to include ... argument in your function, as said in the rasterize documentation:

If x represents points, fun must accept a na.rm argument, either explicitly or through 'dots'.

So you can do something like this:

library(raster)

#generate data
r <- raster(ncols=36, nrows=18)
n <- 1000
set.seed(123)
x <- runif(n) * 360 - 180
y <- runif(n) * 180 - 90
z <- sample(1:1000,n)
xy <- cbind(x, y)

#rasterize
s <- rasterize(xy, r, z, fun=function(x,...)mean(x,na.rm=T), backgroud=0, update=TRUE)
plot(s)
Elia
  • 2,210
  • 1
  • 6
  • 18