#' Overlay a grid and count cell crossings
#'
#' This function overlays a grid on the track generated by the \code{trackPath} function and counts the number of cells crossed by the animal. It is useful for returning count and proportional data abount an animal's path.
#' @param path.list a list object created by the \code{trackPath} function
#' @param xgrid an integer specifying the number of grid cells the arena should be divided into along its width
#' @param ygrid an integer specifying the number of grid cells the arena should be divided into along its height
#' @return If assigned to an object, a list containing the number of cells crossed and the proportion of total cells crossed; if not assigned to an object, a message in the console is returned.
#' @importFrom marmap diag.bathy
#' @export
countCells = function(path.list, xgrid, ygrid) {
grid.matrix = matrix(ncol = 2, nrow = (xgrid * ygrid))
colnames(grid.matrix) = c("x", "y")
grid.matrix[, 1] = rep(seq(from = (path.list$dim.pix[1]/xgrid)/2, to = path.list$dim.pix[1] - (path.list$dim.pix[1]/xgrid)/2, by = path.list$dim.pix[1]/xgrid), times = ygrid)
grid.matrix[, 2] = rep(seq(from = (path.list$dim.pix[2]/ygrid)/2, to = path.list$dim.pix[2] - (path.list$dim.pix[2]/ygrid)/2, by = path.list$dim.pix[2]/ygrid), each = xgrid)
xtrack = c()
ytrack = c()
dat = na.lomf(path.list$position)
for (i in 2:length(path.list$position[,1])) {
track = matrix(ncol = length(round(dat[,1][i - 1]):round(dat[,1][i])), nrow = length(round(dat[,2][i - 1]):round(dat[,2][i])))
colnames(track) = round(dat[,1][i - 1]):round(dat[,1][i])
rownames(track) = round(dat[,2][i - 1]):round(dat[,2][i])
diag.bathy(track, coord = T)
xtrack = append(xtrack, diag.bathy(track, coord = T)[,2])
ytrack = append(ytrack, diag.bathy(track, coord = T)[,1])
}
cells = c()
cells.cross = c()
for (j in 1:length(xtrack)) {
for (k in 1:nrow(grid.matrix)) {
A = abs(xtrack[j] - grid.matrix[k, 1])
B = abs(ytrack[j] - grid.matrix[k, 2])
cells[k] = sqrt((A^2) + (B^2))
}
cells.cross[j] = which(cells == min(cells))[1]
}
message(paste("The animal crossed a total of ", length(unique(cells.cross)), " unique grid cells (", round((length(unique(cells.cross))/(xgrid * ygrid)) * 100), "% of total grid cells)", sep = ""))
flush.console()
invisible(list(cell.count = length(unique(cells.cross)), proportion.cells = length(unique(cells.cross))/(xgrid * ygrid)))
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.