# [R] masking polygons (formerly no subject)

White.Denis@epamail.epa.gov White.Denis at epamail.epa.gov
Fri Feb 14 02:29:03 CET 2003

```> I have two routine tasks that I am wasting time over
> trying to solve. Can anyone help?  I want to display
> the results of some geostatistical analysis quickly in
> R before exporting back to GIS . Does anyone have a trick
> for overlaying a polygon on an image of a krigging surface
> (prmat in spatial) in such a way that the space outside
> the polygon is whited out (so I trim within state
> boundaries)?  Also, has anyone got a function for converting
> decimal degrees to UTM within R itself?
>
> Thanks,
>
> Duncan Golicher

Below is some simple code to illustrate a way to do it.  The idea is to
concatenate the coordinates of the polygon of interest (e.g., state
boundary) to the coordinates describing the plot region (in data space).
This trick assumes that the polygon of interest lies entirely within the
plot region.  Then the polygon shading algorithm treats the polygon of
interest like a hole in the outer polygon and leaves it transparent.  If
the polygon of interest itself has interior holes it may not work.

n <- 50 * 3
x <- runif (n)
y <- runif (n)
x[(seq(n) %% 3) == 0] <- NA
y[(seq(n) %% 3) == 0] <- NA

plot.new ()
range.x <- range (x, na.rm=TRUE)
range.y <- range (y, na.rm=TRUE)
plot.window (range.x, range.y, asp=1)
lines (x, y)

wind.x <- c(range.x, rev (range.x), range.x)
wind.y <- c(range.y, range.y, rev (range.y))

# example polygon
poly.x <- wind.x / 2 + 0.25
poly.y <- wind.y / 2 + 0.25