Created
July 25, 2016 06:55
-
-
Save fdschneider/656ae9f97c4e9e4ee97a88385594aa4d to your computer and use it in GitHub Desktop.
identify and count the size of individual patches in a binary matrix
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# identify and count the size of individual patches | |
patches <- function(x, state) { | |
pattern <- x$cells | |
pattern <- pattern %in% state | |
map <- rep(NA, times = prod(x$dim)) | |
old <- rep(99, times = prod(x$dim)) | |
while(!identical(old[pattern], map[pattern])) { | |
old <- map | |
count = as.integer(1) | |
for(i in which(pattern)) { | |
neighbors <- map[x_with_border][x_to_evaluate[i]+interact] | |
if(all(is.na(neighbors)) ) { | |
map[i] <- count | |
} else { | |
map[i] <- min(neighbors, na.rm = TRUE) | |
} | |
count <- count +1 | |
} | |
} | |
map <- as.factor(map) | |
patchvec <- as.vector(sapply(levels(map), function(i) length(which(map == i) ) )) | |
out <- vector() | |
if(length(patchvec) > 0) out <- sort(patchvec) else out <- NA | |
#out <- data.frame(size = unique(out), freq = sapply(unique(out), function(i) length(which(out >= i)) )) | |
return(out) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment