rvoronoispatstatdirichlet

R - sum of the values of points in different tiles (polygons) of a Voronoi diagram


I have the following df:

  name   x      y
  A      -47   134
  B      -11   311
  C       49   100
  D      -40   138
  E      -33   233
  F       30   134

I'm using the x & y coords to generate a Voronoi tessellation enclosed by a rectangle:

library(spatstat)
library(deldir)

rectangle <- owin(c(-100,100),c(0,400))
points <- ppp(x=df$x,y=df$y,  window = rectangle)
voronoi <- dirichlet(points)
plot(voronoi)

Voronoi diagram

Now say i have another df, df2:

  x       y     value
 -99      2      0.24
  -5      32     0.24
  51      242    0.08
  26      54     0.25

I know I can count the sum of points (in df2) in each polygon of my Voronoi tessellation using spatstat & quadratcount, but what if I want to count the sum of the values in each polygon instead?

To give me something like:

 name   x      y      sum_of_value
   A      -47   134    0.24
   B      -11   311    0.32
   C       49   100    0
   D      -40   138    0
   E      -33   233    0
   F       30   134    0.25

Solution


  • I don't understand your expected output. Using by.ppp I can produce the output below which may be what you want?

    library(spatstat)
    library(deldir)
    df <- structure(list(name = c("A", "B", "C", "D", "E", "F"),
                         x = c(-47L, -11L, 49L, -40L, -33L, 30L),
                         y = c(134L, 311L, 100L, 138L, 233L, 134L)),
                    .Names = c("name", "x", "y"),
                    row.names = 1:6,
                    class = "data.frame")
    rectangle <- owin(c(-100,100),c(0,400))
    points <- ppp(x=df$x,y=df$y,  window = rectangle)
    voronoi <- dirichlet(points)
    plot(voronoi)
    text(df$x, df$y, labels = df$name)
    
    df2 <- structure(list(x = c(-99L, -5L, 51L, 26L),
                          y = c(2L, 32L, 242L, 54L),
                          value = c(0.24, 0.24, 0.08, 0.25)),
                     .Names = c("x", "y", "value"),
                     row.names = 1:4,
                     class = "data.frame")
    
    points2 <- as.ppp(df2, W = rectangle)
    text(df2$x, df2$y, labels = df2$value)
    

    values2 <- by(points2, voronoi, marks)
    df$values <- sapply(values2, sum)
    
    df
    #>   name   x   y values
    #> 1    A -47 134   0.24
    #> 2    B -11 311   0.00
    #> 3    C  49 100   0.49
    #> 4    D -40 138   0.00
    #> 5    E -33 233   0.08
    #> 6    F  30 134   0.00