#'Determine sectors for each point based on trigonometry
#'
#'A full circle is 2*pi, the sector of each point is determined
#'by atan2(y,x), the angle of the point relative to the horizontal line
#'of the introduction site
#'
#'@export
#'
#'@param dataset A dataset to be processed
#'@param nb_sectors Number of sectors to divide the invasion space (default: 8)
#'@param centroid Coordinates of the centroid to center the circle (long, lat; default: -75.675340, 40.415240)
#'@param rotation Number of rotations of the grid wanted (default: 1)
#'
#'@return The same table as \code{dataset} multiplied by the number of rotations, with additional columns:
#'\code{sectors} containing the total number of sectors considered, \code{rotation_nb} containing the rotation considered,
#'\code{sectors_nb} containing the sector number attributed to this cell in this rotation
#'
#'@examples
#' new_dataset <- attribute_sectors(dataset)
attribute_sectors <- function(dataset, nb_sectors = 8, centroid = c(-75.675340, 40.415240), rotation = 1) {
cat(paste(Sys.time(), "Start sector attribution... "))
x = NULL
y = NULL
grid_data <- dataset %>% add_column(theta = NA,
sectors = nb_sectors)
# Calculate theta, the angle between the point and the horizontal line, for each point
for (i in 1:length(grid_data$longitude)) {
x = grid_data$longitude[i] - centroid[1]
y = grid_data$latitude[i] - centroid[2]
grid_data$theta[i] = base::atan2(y,x) + pi
}
# Create a variable for the angle
angle_sector = 2*pi/nb_sectors
# Calculate the angle of each rotation
p = angle_sector/rotation
# Attribute the sector number for each point in each rotation
for (i in 0:(rotation-1)){
grid_data <- grid_data %>% mutate(thetanew = theta - p*i,
thetanew = ifelse(thetanew < 0, thetanew + 2*pi, thetanew),
sector = ceiling((thetanew)/angle_sector)) %>%
dplyr::select(-thetanew)
names(grid_data)[which(names(grid_data) == 'sector')] <- paste("rotation", i+1, sep = "")
}
# Pivot the dataset to obtain the format required for the next analysis
grid_data_sectors <- grid_data %>%
pivot_longer(cols = starts_with("rotation"), names_to = "rotation_nb",
values_to = "sectors_nb", names_prefix = "rotation",
names_transform = list(rotation_nb = as.integer))
cat(paste("Sector attribution completed. \n"))
return(grid_data_sectors)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.