Skip to content

Commit

Permalink
add an improve functions
Browse files Browse the repository at this point in the history
  • Loading branch information
stangandaho committed Jan 31, 2025
1 parent 071c601 commit c760f04
Show file tree
Hide file tree
Showing 24 changed files with 434 additions and 96 deletions.
5 changes: 3 additions & 2 deletions DESCRIPTION
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@ Imports:
ggplot2,
leaflet,
magrittr,
methods,
overlap,
sf,
shiny,
shinyFiles,
shinyTree,
tibble,
tidyr,
rlang
Authors@R: c(
Expand All @@ -28,7 +29,7 @@ Description: Provided tool to edit, extract, visualize and analyze
License: MIT + file LICENSE
Encoding: UTF-8
LazyData: true
RoxygenNote: 7.3.1
RoxygenNote: 7.3.2
Roxygen: list(markdown = TRUE)
Suggests: testthat (>= 3.0.0)
Config/testthat/edition: 3
9 changes: 9 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ importFrom(exifr, read_exif)
# base
importFrom("stats", "setNames")
importFrom("utils", "write.csv")
importFrom("methods", "hasArg")
importFrom("stats", "cov")
importFrom("utils", "read.table")

# dplyr
importFrom(dplyr, as_tibble)
Expand Down Expand Up @@ -158,3 +161,9 @@ importFrom(overlap, overlapPlot)
importFrom(overlap, overlapTrue)
importFrom(overlap, resample)
importFrom(overlap, sunTime)
importFrom(overlap, sunTime)

# sf
importFrom(sf, st_as_sf)
importFrom(sf, st_transform)
importFrom(sf, st_coordinates)
4 changes: 2 additions & 2 deletions R/mm_bootstrap.R
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@
#' mm_boot_CI(est, boots)
#'
#' # alternatively:
#' species_A_gen <- resample(species_A, 1000)
#' species_B_gen <- resample(species_B, 1000)
#' species_A_gen <- mm_resample(species_A, 1000)
#' species_B_gen <- mm_resample(species_B, 1000)
#' boots <- mm_boot_estimates(species_A_gen, species_B_gen, type="Dhat4", cores=1)
#' mean(boots)
#'
Expand Down
69 changes: 41 additions & 28 deletions R/mm_check_location.R
Original file line number Diff line number Diff line change
@@ -1,23 +1,29 @@
#' Interactive Camera Trap Location Adjustment
#'
#' This function launches a shiny application that allows users to visualize and manually adjust the geographic
#' coordinates of camera trap locations. Users can drag points on an interactive map to update the positions
#' This function launches a shiny application that allows users to visualize
#' and manually adjust the geographic coordinates of camera trap locations.
#' Users can drag points on an interactive map to update the positions
#' of camera traps, and the updated dataset is saved to the global environment.
#'
#' @param data A data frame containing the camera trap data to be processed.
#' @param longitude A string representing the column name for longitude in the dataset.
#' @param latitude A string representing the column name for latitude in the dataset.
#' @param location_name A string representing the column name for the location name or unique identifier
#' for each camera trap point.
#' @param coord_system A string specifying the coordinate system of the input data.
#' Choices are `"geographic"` for longitude and latitude, or `"projected"` for projected coordinates.
#' @param crs An integer representing the coordinate reference system (CRS) in EPSG format.
#' Required when `coord_system = "projected"`.
#' @param new_data_name A string specifying the name of the new dataset with updated coordinates to be created
#' in the global environment.
#' @param longitude A string representing the column name for longitude in the
#' dataset.
#' @param latitude A string representing the column name for latitude in
#' the dataset.
#' @param location_name A string representing the column name for the
#' location name or unique identifier for each camera trap point.
#' @param coord_system A string specifying the coordinate system of
#' the input data. Choices are `"geographic"` for longitude and latitude,
#' or `"projected"` for projected coordinates.
#' @param crs An integer representing the coordinate reference system (CRS)
#' in EPSG format. Required when `coord_system = "projected"`.
#' @param new_data_name A string specifying the name of the new dataset with
#' updated coordinates to be created in the global environment.
#'
#' @return A shiny application is launched to display the map and allow manual coordinate adjustments.
#' The modified dataset is saved to the global environment under the name provided in `new_data_name`.
#' @return A shiny application is launched to display the map and allow
#' manual coordinate adjustments.
#' The modified dataset is saved to the global environment under the name
#' provided in `new_data_name`.
#'
#' @examples
#' \dontrun{
Expand All @@ -38,7 +44,8 @@
#' coord_system = "geographic",
#' new_data_name = "updated_camera_traps"
#' )
#' # After adjustments, the updated dataset will be available in the global environment as `updated_camera_traps`.
#' # After adjustments, the updated dataset will be available in the global
#' environment as `updated_camera_traps`.
#' }
#'
#' @import shiny
Expand All @@ -61,24 +68,28 @@ mm_check_location <- function(data,
lat_ <- paste0(dplyr::ensym(latitude))

data <- data %>%
dplyr::mutate(obs = paste0(longitude, latitude)) %>%
dplyr::distinct(obs, .keep_all = TRUE) %>%
dplyr::select(-obs) %>%
dplyr::filter(!is.na(longitude) & !is.na(latitude))
dplyr::mutate("obs" = paste0(!!dplyr::ensym(lon_), !!dplyr::ensym(lat_))) %>%
dplyr::distinct("obs", .keep_all = TRUE) %>%
dplyr::select(-"obs") %>%
dplyr::filter(!is.na(!!dplyr::ensym(lon_)) & !is.na(!!dplyr::ensym(lat_)))


if (coord_system == "projected") {
if(!hasArg(crs))stop("Specify the crs")
if(!methods::hasArg(crs))stop("Specify the crs")
coord <- data %>%
sf::st_as_sf(coords = c(lon_, lat_), crs = crs) %>%
sf::st_transform(crs = 4326) %>%
sf::st_coordinates() %>%
as.data.frame()

}else{
coord <- data %>%
dplyr::rename(X = lon_, Y = lat_)
dplyr::rename("X" = lon_, "Y" = lat_)
}

coord <- coord %>% dplyr::select("X", "Y")
print(coord)

# data to use
if (paste0(dplyr::ensym(location_name)) == "") {
stop("location_name can not be empty")
Expand All @@ -88,7 +99,7 @@ mm_check_location <- function(data,
dplyr::select(- dplyr::all_of(c(lon_, lat_))) %>%
dplyr::bind_cols(coord) %>%
# add location_name column
dplyr::rename('location_name' = plc_)
dplyr::rename("location_name" = plc_)


# shiny
Expand All @@ -104,32 +115,34 @@ mm_check_location <- function(data,
leaflet::addProviderTiles("OpenTopoMap", group = "OpenTopoMap") %>%
leaflet::addLayersControl(
baseGroups = c("OSM", "OSM France", "Natural", "OpenTopoMap"),
options = layersControlOptions(collapsed = T)
options = leaflet::layersControlOptions(collapsed = T)
) %>%
leaflet::addMarkers(lng = data$X,
lat = data$Y,
layerId = data$location_name,
options = markerOptions(draggable = TRUE),
options = leaflet::markerOptions(draggable = TRUE),
popup = data$location_name) %>%
leaflet::setView(lng = data$X[1], lat = data$Y[1], zoom = 8)
})

# Capture the updated coordinates after marker drag event
observeEvent(input$map_marker_dragend, {
shiny::observeEvent(input$map_marker_dragend, {
new_coords <- input$map_marker_dragend # Get the coordinates from the input object
# Update the coordinates in the reactive variable
updated_coords <- dplyr::tibble(X = new_coords$lng,
Y = new_coords$lat,
location_name = new_coords$id)


# Update data replacing new coordinate
coord <- coord %>% dplyr::mutate(location_name = data[["location_name"]])
coord[coord[["location_name"]] == new_coords$id, "X"] <- new_coords$lng
coord[coord[["location_name"]] == new_coords$id, "Y"] <- new_coords$lat


coord <- coord %>%
dplyr::rename("{plc_}" := "location_name",
"{lon_}" := "X",
"{lat_}" := "Y")
dplyr::rename_with(~ c(plc_, lon_, lat_), c("location_name", "X", "Y"))

data_to_return <- data_copy %>%
dplyr::select(- dplyr::all_of(c(lon_, lat_))) %>%
dplyr::left_join(y = coord, by = plc_)
Expand Down
9 changes: 3 additions & 6 deletions R/mm_independence.R
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,7 @@
#' @param datetime A `character` string specifying the name of the column in `data` that contains
#' the datetime values. This argument is required if `data` is provided.
#' @param format A `character` string defining the format used to parse the datetime values in
#' the `datetime` column. This argument is required if `data` is provided and should be
#' in the format recognized by [strptime()].
#' @param deltatime A `numeric` vector of time differences between successive events. This argument
#' is used if `data` is not provided. If `data` is provided, this argument is ignored.
#' the `datetime` column.
#' @param threshold A `numeric` value representing the time difference threshold (in seconds) to
#' determine whether events are independent. Events are considered independent if the time
#' difference between them is greater than or equal to this threshold. The default is 30 minutes
Expand Down Expand Up @@ -51,7 +48,7 @@ mm_independence <- function(data = NULL,
stop("Wrong data provided")
}

dt_str_ <- ifelse(hasArg(datetime), paste0(dplyr::ensym(datetime)), "datetime")
dt_str_ <- ifelse(methods::hasArg(datetime), paste0(dplyr::ensym(datetime)), "datetime")

if (!any(dt_str_ %in% colnames(data))) {
stop(sprintf("%s not found in data", dt_str_))
Expand All @@ -78,7 +75,7 @@ mm_independence <- function(data = NULL,

}else{
original_datetime <- datetime
data <- dplyr::tibble('datetime' := strptime(datetime, format = format)) %>%
data <- dplyr::tibble('{datetime}' := strptime(datetime, format = format)) %>%
dplyr::arrange(datetime)
}

Expand Down
15 changes: 5 additions & 10 deletions R/mm_overlap_estimates.R
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,12 @@
#' @inheritParams overlap::overlapEst
#'
#' @examples
#'# Get example data:
#' data(simulatedData)
#'
#' # Use defaults:
#' mm_overlap_estimates(tigerObs, pigObs)
#' # Dhat1 Dhat4 Dhat5
#' 0.2908618 0.2692011 0.2275000
#'
#' mm_overlap_estimates(tigerObs, pigObs, type="Dhat4")
#' # Dhat4
#'# 0.2692011
#'set.seed(42)
#' species_A <- runif(100, 1.2, 2 * pi)
#' species_B <- runif(100, 0.23, 2 * pi)
#' mm_overlap_estimates(species_A, species_B)
#' mm_overlap_estimates(species_A, species_B, type = "Dhat4")
#'
#'@export

Expand Down
1 change: 1 addition & 0 deletions R/mm_plot_overlap_coef.R
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
#' @examples
#' # Example overlap coefficient matrix
#' overlap_matrix <- matrix(c(1, 0.8, 0.7, 0.8, 1, 0.9, 0.7, 0.9, 1), ncol = 3)
#' colnames(overlap_matrix) <- rownames(overlap_matrix) <- c("A", "B", "C")
#'
#' # Plot lower triangle with shapes
#' mm_plot_overlap_coef(overlap_matrix, side = "lower", show = "shape")
Expand Down
2 changes: 1 addition & 1 deletion R/mm_read.R
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ mm_read <- function(file_path,
...) {

if (!hasArg(sep)) {
sep <- maimer:::check_sep(file_path = file_path)
sep <- check_sep(file_path = file_path)
}

data_read <- read.table(file = file_path,
Expand Down
7 changes: 4 additions & 3 deletions R/mm_temporal_shift.R
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,17 @@
#'
#'
#' @examples
#' library(ggplot2)
#' # Example 1: Using radians as input
#'
#' first_period <- c(1.3, 2.3, 2.5, 5.2, 6.1, 2.3) # Example timestamps for period 1
#' second_period <- c(1.8, 2.2, 2.5) # Example timestamps for period 2
#' result <- mm_temporal_shift(first_period, second_period, plot = T,
#' xcenter = "noon",
#' result <- mm_temporal_shift(first_period, second_period, plot = TRUE, xcenter = "noon",
#' linestyle_1 = list(color = "red", linetype = 1, linewidth = 1),
#' linestyle_2 = list(color = "#004c2f", linetype = 5, linewidth = .5))
#'
#' result$plot+
#' ggplot2::labs(color = "PP")+
#' labs(color = "PP")+
#' theme(legend.position = "top")
#'
#' # Example 2: Using time strings as input
Expand Down
10 changes: 5 additions & 5 deletions R/mm_to_community.R
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#' Convert Data to a Community Matrix
#'
#' The `to_community` function transforms input data into a community matrix where
#' The function transforms input data into a community matrix where
#' rows represent sites, columns represent species, and values indicate the count
#' or abundance of each species at each site.
#'
Expand All @@ -20,20 +20,20 @@
#'
#' @examples
#' # Example data
#' df <- tibble(
#' df <- dplyr::tibble(
#' site = c("A", "A", "B", "B", "C"),
#' species = c("sp1", "sp2", "sp1", "sp3", "sp2"),
#' abundance = c(5, 2, 3, 1, 4)
#' )
#'
#' # Convert to community matrix with counts
#' to_community(df, site_column = site, species_column = species)
#' mm_to_community(df, site_column = site, species_column = species)
#'
#' # Convert to community matrix with abundance
#' to_community(df, site_column = site, species_column = species, size_column = abundance)
#' mm_to_community(df, site_column = site, species_column = species, size_column = abundance)
#'
#' # Fill missing cells with 0
#' to_community(df, site_column = site, species_column = species, values_fill = 0)
#' mm_to_community(df, site_column = site, species_column = species, values_fill = 0)
#'
#' @import dplyr
#' @import tidyr
Expand Down
2 changes: 1 addition & 1 deletion R/mm_to_radian.R
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#' Convert Time to Radians
#' Convert time to radians
#'
#' This function converts time values into radians, which is often used in circular statistics and time-of-day analyses.
#'
Expand Down
9 changes: 5 additions & 4 deletions R/mm_to_time.R
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@
#'
#' This function converts an angle in radians (representing a fraction of a full circle)
#' into a time in the format '%H:%M:%S'. The conversion assumes that the radian value
#' represents a fraction of a 24-hour day (i.e., 0 radians is midnight and 2π radians is the next midnight).
#' represents a fraction of a 24-hour day (i.e., 0 radians is midnight
#' and \eqn{2\pi} radians is the next midnight).
#'
#' @param radian A numeric value or vector representing an angle in radians.
#' The value must lie within the range [0, 2π], where 0 corresponds to midnight
#' (00:00:00) and corresponds to the next midnight (24:00:00).
#' The value must lie within the range \eqn{[0, 2\pi]}, where 0 corresponds to midnight
#' (00:00:00) and \eqn{2\pi} corresponds to the next midnight (24:00:00).
#'
#' @return A character string representing the time in the format '%H:%M:%S'.
#'
Expand All @@ -28,7 +29,7 @@ mm_to_time <- function(radian) {
}

if (all(radian < 0 | radian > 2*pi)) {
stop(sprintf("%f is out of [0, ]", radian))
stop(sprintf("%f is out of [0, 2\u03C0]", radian))
}

fraction_of_day <- radian/(2*pi)
Expand Down
14 changes: 7 additions & 7 deletions R/utils.R
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,8 @@ magrittr::`%>%`
magrittr::`%<>%`



################
#' Parse datetime
#'
#' @description
Expand Down Expand Up @@ -146,16 +148,11 @@ parse_datetime <- function (datetime,
if (all(datetime == "") & allow_empty_output)
return(NA)
datetime_char <- as.character(datetime)

if (grepl(pattern = "%", x = format, fixed = TRUE)) {
out <- as.POSIXct(datetime_char, tz = time_zone, format = format)
}
else {
if (!requireNamespace("lubridate", quietly = TRUE))
stop(paste("package 'lubridate' is required for the specified format",
format))
out <- lubridate::parse_date_time(datetime_char, orders = format,
tz = time_zone, quiet = quiet)
}

if (all(is.na(out)))
stop(paste0("Cannot read datetime format in ", deparse(substitute(datetime)),
". Output is all NA.\n", "expected: ", format,
Expand All @@ -170,6 +167,9 @@ parse_datetime <- function (datetime,
return(out)
}



########################
#' Select column
#'
#' @description
Expand Down
Loading

0 comments on commit c760f04

Please sign in to comment.