R/Points_in_polygon.R

Defines functions test_fun points_in_polygon

#' Extracts points in polygon
#'
#' @md
#' @description adapted from [Will R Chase's Texturizer Function](
#' https://github.com/will-r-chase/aRt/blob/master/July_textures/pebbles.R)
#'
#' @param points A data.frame with the environment of points.
#' @param polygon A data.frame with the polygons to check inside.
points_in_polygon <- function(
  points,
  polygon,
  polygon.id = "id",
  ploygon.x  = "x",
  polygon.y  = "y",
  points.x   = "x",
  points.y   = "y"
){

  tmp <- split(
    dplyr::select(
      polygon,
      {{ploygon.x}},
      {{polygon.y}}
      ),
    polygon[{{polygon.id}}]
    )

  tmp <- map(
    tmp,
    ~mgcv::in.out(as.matrix(.x), as.matrix(points))
    )

  tmp <- map(tmp, ~cbind(.x, points))
  tmp <- bind_rows(tmp, .id = "id")
  print(paste(names(tmp), collapse = " ,"))

  tmp <- rename(tmp, "in_polygon" = ".x")

  return(tmp)
}




library(tidyverse)
df <- data.frame(

  x = sample(1:100, 100, replace = TRUE),
  y =  sample(1:100, 100, replace = FALSE),
  id = letters[0:99%%3+1]

)




pts <- ambient::long_grid(x =  seq(1, 100, .1),
        y = seq(1, 100, .1)) %>%
  tibble()



points_in_polygon(pts,
                  df)


 tmp <- df %>%
  select(x, y) %>%
  split(.,  df$id)
  map(tmp, ~mgcv::in.out(as.matrix(.x), as.matrix(pts))) %>%
    map(., ~cbind(.x, pts)) %>%
    bind_rows(.id = "id") ->tmp

  tmp%>%
    ggplot(aes(x,y, color = .x))+
    geom_point()

 df %>%
   ggplot(aes(x,y, fill = id))+
   geom_polygon()


 test_fun <- function(
   var
 ){
  map(mtcars, sum(.x[{{var}}]) )
 }


 test_fun("cyl")
delabj/genArt documentation built on March 25, 2021, 11:56 p.m.