content
stringlengths
0
14.9M
filename
stringlengths
44
136
#' Assert Message Based on Type #' #' This function asserts a message based on the type specified. #' It can either push the message to an AssertCollection, print a warning, or stop execution with an error message. #' #' @param message A character string representing the message to be asserted. #' @param assertion_fail A character string indicating the action to take if the assertion fails. Can be an AssertCollection, "warning", or "stop" (default). #' @return None #' @export assertion_message <- function(message, assertion_fail = "stop") { if (inherits(assertion_fail, "AssertCollection")) { assertion_fail$push(message) } else if (assertion_fail == "warning") { warning(message) } else if (assertion_fail == "stop") { stop(message) } }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/assert_message.R
#' Assert No Duplicates in Group #' #' This function asserts that there are no duplicate rows in the specified columns of a data frame. #' It groups the data frame by the specified columns, counts the number of unique values for each group, and checks if there are any groups with more than one row. #' If there are, it prints an error message and stops the execution (unless `assertion_fail` is set to "warn"). #' #' @param df A data frame. #' @param group_vars A character vector of column names. #' @param assertion_fail A character string indicating the action to take if the assertion fails. Can be "stop" (default) or "warn". #' @return The input data frame. #' @export assert_no_duplicates_in_group <- function(df, group_vars, assertion_fail = "stop") { Number_rows <- NULL # Check whether the group variables exist in the data frame if (!all(group_vars %in% names(df))) { assertion_message( paste("Not enough columns to determine duplicate rows", "The following columns are missing:", paste(setdiff(group_vars, names(df)), collapse = "\n"), sep = "\n" ), assertion_fail = assertion_fail ) } # Check whether the group variables exist in the data frame if (any(group_vars %in% names(df))) { # Create a Tibble result <- df %>% dplyr::ungroup() %>% dplyr::group_by_at(dplyr::vars(dplyr::one_of(group_vars))) %>% dplyr::summarise(Number_rows = dplyr::n()) %>% dplyr::mutate(Number_double_per_field = Number_rows - 1) # Count the number of duplicates Count_doubles <- count_more_than_1(result$Number_rows) Total_double <- sum(result$Number_double_per_field) # If assertion succeeds, result must be TRUE result <- TRUE variables <- paste(group_vars, collapse = ", ") # If number of duplicates is more than 0, it will be displayed in the assert message. if (Count_doubles > 0) { result <- paste( "In the combination of the columns", variables, "there are", Count_doubles, "rows that appear more often. The total number of duplicated rows is", Total_double ) assertion_message(result, assertion_fail) } } return(invisible(df)) }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/assert_no_duplicates_in_group.R
#' check double columns #' #' Check whether two dataframes have intersecting column names. #' @param x Data frame x. #' @param y Data frame y. #' @param connector The connector columns as strings. Also possible as vector. #' @return Message informing about overlap in columns between the dataframes. #' @examples #' check_double_columns(mtcars, iris) #' #' @family tests #' @export check_double_columns <- function(x, y, connector = NULL) { Differences <- intersect(names(x), names(y)) Differences_without_connector <- setdiff(Differences, connector) Differences_count <- length(Differences_without_connector) if (Differences_count > 0) { message(paste(Differences_without_connector, collapse = "\n")) stop("Overlap in column names") } else { message("There are no overlapping columns between the dataframes") } }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/check_double_columns.R
#' Check for Duplicate Rows in Selected Columns #' #' This function checks if there are any duplicate rows in the specified columns of a data frame. #' It prints the unique rows and returns a boolean indicating whether the number of rows in the original data frame is the same as the number of rows in the data frame with duplicate rows removed. #' #' @param data A data frame. #' @param columns A character vector of column names. #' @return A logical value indicating whether the number of rows in the original data frame is the same as the number of rows in the data frame with duplicate rows removed. #' @examples #' # Create a data frame #' df <- data.frame(a = c(1, 2, 3, 1), b = c(4, 5, 6, 4), c = c(7, 8, 9, 7)) #' # Check for duplicate rows in the first two columns #' check_duplicates(df, c("a", "b")) #' #' @export check_duplicates <- function(data, columns) { # Select the specified columns selected_columns <- data %>% dplyr::select(dplyr::all_of(columns)) # Remove duplicate rows unique_rows <- selected_columns %>% dplyr::distinct() # Print the unique rows message(unique_rows) # Check if the number of rows in the original data frame is the same as the number of rows in the data frame with duplicate rows removed if (nrow(selected_columns) == nrow(unique_rows)) { return(TRUE) } else { return(FALSE) } }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/check_duplicates.R
#' Check for No Duplicate Rows #' #' This function checks if there are any duplicate rows in the provided dataframe. #' If there are duplicate rows, a message is added to the provided collection. #' #' @param dataframe A dataframe. #' @param collection A list to store the message if there are duplicate rows. #' @param unique_columns Default is NULL. If provided, these are the columns to check for uniqueness. #' @return The updated collection. #' @examples #' # Create a dataframe with some duplicate rows #' dataframe <- data.frame(a = c(1, 1, 2), b = c(2, 2, 3)) #' collection <- checkmate::makeAssertCollection() #' check_no_duplicate_rows(dataframe, collection, c("a", "b")) #' @export check_no_duplicate_rows <- function(dataframe, collection, unique_columns = NULL) { if (!is.null(unique_columns) && !checkmate::testNames(unique_columns, subset.of = names(dataframe))) { collection$push(paste("Insufficient columns to determine duplicate rows", "The following columns are missing:", paste(setdiff(unique_columns, names(dataframe)), collapse = "\n"), sep = "\n" )) return(collection) } assert_no_duplicates_in_group(dataframe, group_vars = unique_columns, collection) return(collection) }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/check_no_duplicate_rows.R
#' Check for No Duplicates in Group #' #' This function checks if there is exactly one row per group in the provided dataframe. #' If there are multiple rows per group, the assertion fails. #' #' @param dataframe The dataframe to be checked. #' @param group_variables The group variables as a character vector. The default is NULL. #' @param assertion_fail How the function reacts to a failure. This can be a "warning", where only a warning is given on the failure, #' or a "stop", where the function execution is stopped and the message is displayed, or an "AssertCollection", where the failure message is added to an assertion collection. #' @family assertions #' @family tests #' @examples #' # Create a dataframe with some groups having more than one row #' dataframe <- data.frame(a = c(1, 1, 2), b = c(2, 2, 3), c = c("x", "x", "y")) #' # Check the uniqueness of rows per group #' check_no_duplicates_in_group(dataframe) #' @export check_no_duplicates_in_group <- function(dataframe, group_variables = NULL, assertion_fail = "stop") { row_count <- NULL # Check if the variables to test exist in the dataframe, and give a message otherwise if (!is.null(group_variables) && !all(group_variables %in% names(dataframe))) { assertion_message(paste("Insufficient columns to determine duplicate rows", "The following columns are missing:", paste(setdiff(group_variables, names(dataframe)), collapse = "\n"), sep = "\n"), assertion_fail = assertion_fail) } # Check if the given columns exist in the dataframe before grouping if (any(group_variables %in% names(dataframe))) { result <- dataframe %>% dplyr::ungroup() %>% dplyr::group_by_at(dplyr::vars(dplyr::one_of(group_variables))) %>% dplyr::summarise(row_count = dplyr::n()) %>% dplyr::mutate(duplicates_per_field = row_count - 1) duplicate_count <- count_more_than_1(result$row_count) total_duplicates <- sum(result$duplicates_per_field) result <- TRUE variables <- paste(group_variables, collapse = ", ") if (duplicate_count > 0) { result <- paste("In the combination of the columns", variables, "there are", duplicate_count, "rows that occur more than once. The total number of duplicate rows is", total_duplicates) assertion_message(result, assertion_fail) } } return(invisible(dataframe)) }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/check_no_duplicates_in_group.R
#' Check for Numeric or Integer Type #' #' This function checks if the specified column in the provided dataframe has a numeric or integer type. #' It uses the checkmate::assert_numeric or checkmate::assert_integer function to perform the assertion, #' depending on the value of the `field_type` parameter. #' #' @param column_name A character vector or string with the column name to be tested. #' @param dataframe The dataframe that contains the column. #' @param column_prefix Default is NULL. If provided, this text is prepended to the variable name in the assertion message. #' @param field_type Default is "numeric". Specify "integer" to check if the column has an integer type. This parameter must be either "integer" or "numeric". #' @param ... The remaining parameters are passed to the function assert_numeric or assert_integer. #' @family assertions #' @family tests #' @examples #' # Create a dataframe with a numeric column #' dataframe <- data.frame(a = c(1, 2, 3)) #' # Check the numeric type of the 'a' column #' check_numeric_or_integer_type("a", dataframe) #' @export check_numeric_or_integer_type <- function(column_name, dataframe, column_prefix = NULL, field_type = "numeric", ...) { # Check if field_type is either "integer" or "numeric" if (!(field_type %in% c("integer", "numeric"))) { stop("field_type must be either 'integer' or 'numeric'") } if (field_type == "integer") { checkmate::assert_integer(dataframe[[column_name]], .var.name = trimws(paste(column_prefix, column_name)), ...) } else { checkmate::assert_numeric(dataframe[[column_name]], .var.name = trimws(paste(column_prefix, column_name)), ...) } }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/check_numeric_or_integer_type.R
#' Check for POSIXct Type #' #' This function checks if the specified column in the provided dataframe has a POSIXct type. #' It uses the checkmate::assert_posixct function to perform the assertion. #' #' @param column_name A character vector or string with the column name to be tested. #' @param dataframe The dataframe that contains the column. #' @param column_prefix Default is NULL. If provided, this text is prepended to the variable name in the assertion message. #' @param ... The remaining parameters are passed to the function assert_posixct. #' @family assertions #' @family tests #' @examples #' # Create a dataframe with a POSIXct column #' dataframe <- data.frame(date = as.POSIXct("2023-10-04")) #' # Check the POSIXct type of the 'date' column #' check_posixct_type("date", dataframe) #' @export check_posixct_type <- function(column_name, dataframe, column_prefix = NULL, ...) { checkmate::assert_posixct(dataframe[[column_name]], .var.name = trimws(paste(column_prefix, column_name)), ... ) }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/check_posixct_type.R
#' Create dataset summary statistics table #' #' This function creates a summary statistics table for a dataframe, providing insights into #' the nature of the data contained within. It includes detailed statistics for each column, #' such as column types, missing value percentages, minimum and maximum values for numeric #' columns, patterns for character columns, uniqueness of identifiers, and distributions. #' #' @param df_input A dataframe for which to create a summary statistics table. #' @return A tibble with comprehensive summary statistics for each column in the input dataframe. #' @importFrom purrr map_chr map_dbl map_lgl possibly #' @export create_dataset_summary_table <- function(df_input) { # Store column names column_names <- names(df_input) # Store column types column_types <- purrr::map_chr(df_input, get_first_element_class) # Calculate missing value percentages missing_value_percentages <- colMeans(is.na(df_input)) * 100 # Find minimum and maximum values for numeric columns min_values <- purrr::map_dbl(df_input, find_minimum_value) max_values <- purrr::map_dbl(df_input, find_maximum_value) # Check for uniqueness of identifiers unique_identifiers <- purrr::map_lgl(column_names, is_unique_column, data_frame = df_input) # Calculate distribution statistics distribution_stats <- purrr::map_chr(df_input, get_distribution_statistics) # Calculate distribution percentages distribution_percentages <- purrr::map_chr(df_input, calculate_category_percentages) # Create a tibble with all summary statistics summary_table <- tibble::tibble( column_name = column_names, column_type = column_types, missing_value_percentage = missing_value_percentages, min_value = min_values, max_value = max_values, unique_identifier = unique_identifiers, distribution_statistics = distribution_stats, distribution_percentages = distribution_percentages ) return(summary_table) } #' Check if a column in a dataframe has unique values #' #' @param column_name The name of the column to check for uniqueness. #' @param data_frame A dataframe containing the column to check. #' @return \code{TRUE} if the column has unique values, \code{FALSE} otherwise. #' @export #' @examples #' # Create a dataframe with a unique ID column #' data_frame <- tibble::tibble( #' id = c(1, 2, 3, 4, 5), #' value = c("a", "b", "c", "d", "e") #' ) #' is_unique_column("id", data_frame) # Returns TRUE #' #' # Create a dataframe with duplicate values in the ID column #' data_frame <- tibble::tibble( #' id = c(1, 2, 3, 4, 5, 1), #' value = c("a", "b", "c", "d", "e", "a") #' ) #' is_unique_column("id", data_frame) # Returns FALSE is_unique_column <- function(column_name, data_frame) { column_values <- data_frame %>% dplyr::pull(column_name) return(nrow(data_frame) == length(unique(column_values))) } #' Retrieve the class of the first element of a vector #' #' @param input_vector A vector whose first element's class is to be retrieved. #' @return The class of the first element of the input vector. #' @export #' @examples #' # Get the class of the first element in a numeric vector #' get_first_element_class(c(1, 2, 3)) # Returns "numeric" #' #' # Get the class of the first element in a character vector #' get_first_element_class(c("apple", "banana", "cherry")) # Returns "character" get_first_element_class <- function(input_vector) { return(class(input_vector)[1]) } #' Find the minimum numeric value in a vector, ignoring non-numeric values #' #' @param numeric_vector A vector from which to find the minimum numeric value. #' @return The minimum numeric value in the input vector, or NA if none exist. #' @export #' @examples #' # Find the minimum of a numeric vector #' find_minimum_value(c(3, 1, 4, 1, 5, 9)) # Returns 1 #' #' # Find the minimum of a mixed vector with non-numeric values #' find_minimum_value(c(3, 1, 4, "two", 5, 9)) # Returns 1 #' #' # Attempt to find the minimum of a vector with only non-numeric values #' find_minimum_value(c("one", "two", "three")) # Returns NA find_minimum_value <- function(numeric_vector) { if (is.numeric(numeric_vector)) { return(min(numeric_vector, na.rm = TRUE)) } else { return(NA) } } #' Find the maximum numeric value in a vector, ignoring non-numeric values #' #' @param numeric_vector A vector from which to find the maximum numeric value. #' @return The maximum numeric value in the input vector, or NA if none exist. #' @export #' @examples #' # Find the maximum of a numeric vector #' find_maximum_value(c(3, 1, 4, 1, 5, 9)) # Returns 9 #' #' # Find the maximum of a mixed vector with non-numeric values #' find_maximum_value(c(3, 1, 4, "two", 5, 9)) # Returns 9 #' #' # Attempt to find the maximum of a vector with only non-numeric values #' find_maximum_value(c("one", "two", "three")) # Returns NA find_maximum_value <- function(numeric_vector) { if (is.numeric(numeric_vector)) { return(max(numeric_vector, na.rm = TRUE)) } else { return(NA) } } #' Compute distribution statistics for a numeric vector #' #' This function computes summary statistics such as quartiles, mean, and standard deviation for a numeric vector. #' #' @param data_vector A numeric vector for which to compute summary statistics. #' @return A character string describing the summary statistics of the input vector. #' @export #' @examples #' # Compute summary statistics for a numeric vector #' data_vector <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) #' get_distribution_statistics(data_vector) get_distribution_statistics <- function(data_vector) { if (is.numeric(data_vector)) { calculated_quantiles <- stats::quantile(data_vector, probs = c(0.25, 0.5, 0.75), na.rm = TRUE) calculated_summary_stats <- c( Mean = mean(data_vector, na.rm = TRUE), Std_Dev = stats::sd(data_vector, na.rm = TRUE) ) formatted_output <- paste( "Q1 =", calculated_quantiles[1], " | median =", calculated_quantiles[2], " | Q3 = ", calculated_quantiles[3], " | mean =", format(calculated_summary_stats["Mean"], digits = 3), " | stdev =", format(calculated_summary_stats["Std_Dev"], digits = 3) ) return(formatted_output) } else if (is.character(data_vector)) { # Filter out non-numeric characters numeric_elements <- grepl("^\\d*\\.?\\d*$", data_vector) if (any(numeric_elements)) { numeric_values <- as.numeric(data_vector[numeric_elements]) calculated_quantiles <- stats::quantile(numeric_values, probs = c(0.25, 0.5, 0.75), na.rm = TRUE) calculated_summary_stats <- c( Mean = mean(numeric_values, na.rm = TRUE), Std_Dev = stats::sd(numeric_values, na.rm = TRUE) ) formatted_output <- paste( "Q1 =", calculated_quantiles[1], " | median =", calculated_quantiles[2], " | Q3 = ", calculated_quantiles[3], " | mean =", format(calculated_summary_stats["Mean"], digits = 3), " | stdev =", format(calculated_summary_stats["Std_Dev"], digits = 3) ) return(formatted_output) } else { return(NA) } } else { return(NA) } } #' Calculate the percentage of categories in a data vector #' #' This function calculates the percentage of each category in a given data vector and returns the top 10 categories along with their percentages. #' If the data vector is of Date class, it is converted to POSIXct. If the sum of the percentages is not 100%, an "Other" category is added to make up the difference, but only if the number of unique values exceeds 10. #' If the data vector is of POSIXct class and the smallest percentage is less than 1%, the function returns "Not enough occurrences." #' #' @param data_vector A vector of categorical data. #' @return A character string detailing the top 10 categories and their percentages, or a special message indicating not enough occurrences or unsupported data type. #' @export #' @examples #' # Example with a character vector #' data_vector <- c("cat", "dog", "bird", "cat", "dog", "cat", "other") #' calculate_category_percentages(data_vector) #' #' # Example with a Date vector #' data_vector <- as.Date(c("2020-01-01", "2020-01-02", "2020-01-03")) #' calculate_category_percentages(data_vector) calculate_category_percentages <- function(data_vector) { # Initialize variables percentages <- n <- percent <- categories <- .data <- NULL # Convert Date objects to POSIXct if (inherits(data_vector, "Date")) { data_vector <- as.POSIXct(data_vector) } # Check if data_vector is a POSIXct object if (!lubridate::is.POSIXct(data_vector)) { # Calculate frequencies and percentages for non-Date vectors frequency_table <- janitor::tabyl(data_vector) %>% dplyr::arrange(dplyr::desc(n)) %>% dplyr::mutate(percent = n / sum(n) * 100) %>% dplyr::filter(!is.na(.data)) %>% dplyr::slice_max(order_by = percent, n = 10) categories <- frequency_table$data_vector percentages <- format(round(frequency_table$percent, 2), nsmall = 2) # Adjust percentages if total is not 100% and there are more than 10 unique values if (sum(as.numeric(percentages)) < 100 && length(unique(data_vector)) > 10) { percentages <- c(percentages, sprintf("%.2f", 100 - sum(as.numeric(percentages)))) categories <- c(categories, "Other") } else { percentages[length(percentages)] <- sprintf("%.2f", 100 - sum(as.numeric(percentages[-length(percentages)]))) } result <- paste0(categories, ": (", percentages, "%)", collapse = " | ") return(result) } else { # Calculate frequencies and percentages for POSIXct vectors frequency_table <- janitor::tabyl(data_vector) %>% dplyr::arrange(dplyr::desc(n)) %>% dplyr::mutate(percent = n / sum(n) * 100) %>% dplyr::filter(!is.na(.data)) %>% dplyr::slice_max(order_by = percent, n = 10) categories <- as.character(frequency_table$data_vector) percentages <- format(round(frequency_table$percent, 2), nsmall = 2) # Adjust percentages if total is not 100% and there are more than 10 unique values if (sum(as.numeric(percentages)) < 100 && length(unique(data_vector)) > 10) { percentages <- c(percentages, sprintf("%.2f", 100 - sum(as.numeric(percentages)))) categories <- c(categories, "Other") } else { percentages[length(percentages)] <- sprintf("%.2f", 100 - sum(as.numeric(percentages[-length(percentages)]))) } # Check if the smallest percentage is less than 1% if (as.numeric(percentages[1]) < 1) { return("Not enough occurrences") } else { result <- paste0(categories, ": (", percentages, "%)", collapse = " | ") return(result) } } return("Data type not supported") }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/create_dataset_summary_table.R
#' Duplicates in column #' #' Searches for duplicates in a data frame column. #' #' @param df Data frame. #' @param col Column name. #' @return Rows containing duplicated values. #' @family tests #' @examples #' duplicates_in_column(mtcars, "mpg") #' #' @export duplicates_in_column <- function(df, col) { ## Check if object "df" is a data frame. if (!is.data.frame(df)) { return(warning("df is not a data frame")) } ## Check if column exists in df. if (!col %in% names(df)) { return(warning("The specified column does not exist in the data frame.")) } values_col <- df[[col]] duplicates <- unique(values_col[duplicated(values_col)]) duplicates_df <- df[values_col %in% duplicates, ] return(duplicates_df) }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/duplicates_in_column.R
#' Find Common Columns Between Data Frames #' #' This function identifies common column names between multiple data frames. #' It takes a variable number of data frames as input and returns a character #' vector containing the common column names. #' #' @param ... A variable length list of data frames. #' #' @return A character vector of column names found in common between all data frames. #' #' @examples #' df1 <- data.frame(a = c(1, 2, 3), b = c(4, 5, 6)) #' df2 <- data.frame(a = c(7, 8, 9), b = c(10, 11, 12), c = c(13, 14, 15)) #' common_columns <- find_common_columns(df1, df2) #' print(common_columns) #' #' @export find_common_columns <- function(...) { list_of_data_frames <- list(...) column_names_list <- lapply(list_of_data_frames, names) common_columns <- Reduce(intersect, column_names_list) return(common_columns) }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/find_common_columns.R
#' Find pattern in R scripts #' #' Function to search for a pattern in R scripts. #' #' @param pattern Pattern to search #' @param path Directory to search in #' @param case.sensitive Whether pattern is case sensitive or not #' @param comments whether to search in commented lines #' @return Dataframe containing R script paths #' @export find_pattern_r <- function(pattern, path = ".", case.sensitive = TRUE, comments = FALSE) { dt <- findR::findRscript(path, pattern = pattern, case.sensitive = case.sensitive, show.results = TRUE, comments = comments) dt <- unique(dt[1]) return(dt) }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/find_pattern_r.R
#' Get values of column #' #' A function to determine what kind of values are present in columns. #' @param df The dataframe #' @param column Column to get values from. #' @return The class of the column values #' @examples #' get_values(mtcars, "mpg") #' #' @export get_values <- function(df, column) { if (inherits(df[[column]], "numeric")) { len <- length(unique(df[[column]])) ifelse(len > 15, return("Numeric values"), return(paste(unique(stats::na.omit(df[[column]])), sep = "", collapse = ", ")) ) } else if (inherits(df[[column]], "character")) { return(paste(range(df[[column]], na.rm = T), collapse = ", ")) } else if (inherits(df[[column]], "logical")) { return("TRUE, FALSE") } else { return("NA") } }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/get_values.R
#' Identify Possible Join Pairs Between Data Frames #' #' This function identifies potential join pairs between two data frames based on the overlap #' between the distinct values in their columns. It returns a data frame showing the possible join pairs. #' #' @param ... A list of two data frames. #' @param similarity_cutoff The minimal percentage of overlap between the distinct values in the columns. #' #' @return A data frame showing candidate join pairs. #' #' @examples #' identify_join_pairs(iris, iris3) #' #' @export identify_join_pairs <- function(..., similarity_cutoff = 0.20) { data_frame1_column <- data_frame2_column <- score <- NULL data_frames <- list(...) df_pairs <- expand.grid(data_frame1_column = names(as.data.frame(data_frames[[1]])), data_frame2_column = names(as.data.frame(data_frames[[2]]))) calculate_similarity_score <- function(column1, column2) { unique_values_df1 <- stats::na.omit(kit::funique(as.data.frame(data_frames[[1]])[[column1]])) unique_values_df2 <- stats::na.omit(kit::funique(as.data.frame(data_frames[[2]])[[column2]])) similarity_score <- length(intersect(unique_values_df1, unique_values_df2)) / length(unique_values_df1) return(similarity_score) } df_pairs <- df_pairs %>% dplyr::mutate(score = purrr::map2_dbl(.x = data_frame1_column, .y = data_frame2_column, .f = calculate_similarity_score)) %>% dplyr::filter(score > similarity_cutoff) %>% dplyr::arrange(dplyr::desc(score)) return(df_pairs) }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/identify_join_pairs.R
#' Identify Outliers in a Data Frame Column #' #' This function identifies outliers in a specified column of a data frame. #' It returns a tibble containing the unique values, tally, and whether it is an outlier or not. #' #' @param df The data frame. #' @param var The column to check for outliers. #' #' @return A tibble containing the unique values, tally, and whether each value is an outlier or not. #' #' @examples #' df <- data.frame(a = c(1, 2, 3, 100, 101), b = c(4, 5, 6, 7, 8), c = c(7, 8, 9, 100, 101)) #' outliers <- identify_outliers(df, "a") #' print(outliers) #' #' @export identify_outliers <- function(df, var) { n <- NULL check <- dplyr::select(.data = df, {{ var }}) %>% dplyr::group_by({{ var }}) %>% dplyr::tally() %>% dplyr::mutate(outlier = (n < stats::quantile(n, 0.05) | n > stats::quantile(n, 0.95))) return(check) }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/identify_outliers.R
#' MD complete cases #' #' Print the complete cases of the data. #' #' @param data The data frame. #' @param digits Default: 1. number of digits for rounding. #' @return Message with the number of rows, number of rows with missing values and the percentage of complete rows. #' @examples #' # example code #' md_complete_cases(iris) #' #' iris$Sepal.Length[5] <- NA_character_ #' md_complete_cases(iris) #' #' @export md_complete_cases <- function(data, digits = 1) { Number_of_rows <- nrow(data) Number_of_rows_complete <- sum(stats::complete.cases(data)) message("Number of rows in the data: ", Number_of_rows, "\n", "Number of rows without missing values: ", Number_of_rows_complete, "\n", "Percentage complete rows: ", round((Number_of_rows_complete / Number_of_rows) * 100, digits = digits), "%", sep = "" ) }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/md_complete_cases.R
#' Construct Regex for Matching Function Parameter Content #' #' This function constructs a regex pattern for matching the content of a parameter in a function. #' It uses the `base::paste0` function to construct the regex pattern. #' #' @param parameter The parameter whose value is to be searched in a function. #' @return A regex pattern as a character string. #' @examples #' # Create a parameter name #' parameter <- "my_parameter" #' # Construct a regex pattern for matching the content of the parameter #' pattern <- regex_content_parameter(parameter) #' #' @export regex_content_parameter <- function(parameter) { base::paste0( "(?<=", parameter, "\\s{0,20}\\=\\s{0,20}\").*" ) }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/regex_content_parameter.R
#' Generate regular expression of a time. #' #' This function generates a regular expression for time based on the input format. #' #' @param format The format of the time. Possible values are: #' \itemize{ #' \item{"hh:mm"}: to generate "09:05". #' \item{"h:m"}: to generate "9:5". #' \item{"hh:mm:ss"}: to generate "09:05:00". #' \item{"h:m:s"}: to generate "9:5:0". #' \item{"hh:mm:ss AM/PM"}: to generate "09:05:00 AM". #' \item{"h:m:s AM/PM"}: to generate "9:5:0 AM". #' } #' #' @return A regular expression. #' #' @examples #' regex_time("hh:mm") #' regex_time("h:m") #' regex_time("hh:mm:ss") #' regex_time("h:m:s") #' regex_time("hh:mm:ss AM/PM") #' regex_time("h:m:s AM/PM") #' #' @export regex_time <- function(format = "hh:mm") { formats <- c( "hh:mm" = "^[0-2][0-9]:[0-5][0-9]$", "h:m" = "^([1-2])?[0-9]:([1-5])?[0-9]$", "hh:mm:ss" = "^([0-1]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$", "h:m:s" = "^([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$", "hh:mm:ss AM/PM" = "^(1[0-2]|0?[1-9]):([0-5][0-9]) ?([AaPp][Mm])$", "h:m:s AM/PM" = "^([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]) ?([AaPp][Mm])$" # Add more formats here if needed ) return(formats[format]) }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/regex_time.R
#' Generate regular expression of a year date. #' #' This function generates a regular expression for year date based on the input format. #' #' @param format The format of the year date. Possible values are: #' \itemize{ #' \item{"yyyy"}: to generate "2023". #' \item{"yyyy-MM-dd"}: to generate "2023-09-29". #' \item{"yyyy/MM/dd"}: to generate "2023/09/29". #' \item{"yyyy.MM.dd"}: to generate "2023.09.29". #' \item{"yyyy-M-d"}: to generate "2023-9-29". #' \item{"yyyy/M/d"}: to generate "2023/9/29". #' \item{"yyyy.M.d"}: to generate "2023.9.29". #' \item{"yyyy-MM-dd HH:mm:ss"}: to generate "2023-09-29 12:34:56". #' \item{"yyyy/MM/dd HH:mm:ss"}: to generate "2023/09/29 12:34:56". #' \item{"yyyy-MM-dd HH:mm"}: to generate "2023-09-29 12:34". #' \item{"yyyy/MM/dd HH:mm"}: to generate "2023/09/29 12:34". #' } #' #' @return A regular expression. #' #' @examples #' regex_year_date("yyyy") #' regex_year_date("yyyy-MM-dd") #' regex_year_date("yyyy/MM/dd") #' regex_year_date("yyyy.MM.dd") #' regex_year_date("yyyy-M-d") #' regex_year_date("yyyy/M/d") #' regex_year_date("yyyy.M.d") #' regex_year_date("yyyy-MM-dd HH:mm:ss") #' regex_year_date("yyyy/MM/dd HH:mm:ss") #' regex_year_date("yyyy-MM-dd HH:mm") #' regex_year_date("yyyy/MM/dd HH:mm") #' #' @export regex_year_date <- function(format = "yyyy") { formats <- c( "yyyy" = "^\\d{4}$", "yyyy-MM-dd" = "^\\d{4}-\\d{2}-\\d{2}$", "yyyy/MM/dd" = "^\\d{4}/\\d{2}/\\d{2}$", "yyyy.MM.dd" = "^\\d{4}\\.\\d{2}\\.\\d{2}$", "yyyy-M-d" = "^\\d{4}-\\d{1,2}-\\d{1,2}$", "yyyy/M/d" = "^\\d{4}/\\d{1,2}/\\d{1,2}$", "yyyy.M.d" = "^\\d{4}\\.\\d{1,2}\\.\\d{1,2}$", "yyyy-MM-dd HH:mm:ss" = "^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$", "yyyy/MM/dd HH:mm:ss" = "^\\d{4}/\\d{2}/\\d{2} \\d{2}:\\d{2}:\\d{2}$", "yyyy-MM-dd HH:mm" = "^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}$", "yyyy/MM/dd HH:mm" = "^\\d{4}/\\d{2}/\\d{2} \\d{2}:\\d{2}$" ) return(formats[format]) }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/regex_year_date.R
#' Remove Duplicates and NA Values from Input #' #' This function removes duplicate values and NA values from the input. #' It first removes NA values from the input using the `na.omit` function from the `stats` package. #' Then it removes duplicate values from the result using the `unique` function. #' #' @param input A vector or data frame. #' @return A vector or data frame with duplicate values and NA values removed. #' @examples #' # Create a vector with duplicate values and NA values #' input <- c(1, 2, NA, 2, NA, 3, 4, 4, NA, 5) #' # Remove duplicate values and NA values #' output <- remove_duplicates_and_na(input) #' print(output) #' #' @export remove_duplicates_and_na <- function(input) { # Remove NA values input <- stats::na.omit(input) # Remove duplicate values input <- unique(input) return(input) }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/remove_duplicates_and_na.R
# Retrieves all created functions within a Rscript #' retrieve_function_calls #' #' @param script_name The script to search functions in #' #' @return dataframe #' @export #' retrieve_function_calls <- function(script_name) { # Read the script file file <- readLines(script_name) # Initialize empty vectors to hold function names, their arguments, and bodies function_name <- character() arguments <- character() function_body <- character() # Iterate over each line in the script file for (i in 1:length(file)) { # Extract the function names and arguments using regex pattern <- stringr::str_match(file[i], pattern = "(\\w+)\\s*<-\\s*function\\((.*)\\)\\s*\\{" ) # If a function definition is found if (!is.na(pattern[1, 1])) { function_name <- c(function_name, pattern[1, 2]) arguments <- c(arguments, pattern[1, 3]) # Initialize counter for open brackets open_brackets <- 1 # Initialize function body with the current line body <- file[i] # Start from the next line j <- i + 1 while (open_brackets > 0 && j <= length(file)) { # Update the count of open and close brackets open_brackets <- open_brackets + length(gregexpr("\\{", file[j])[[1]]) open_brackets <- open_brackets - length(gregexpr("\\}", file[j])[[1]]) # Add the line to the function body body <- paste(body, file[j], sep = "\n") # Move to the next line j <- j + 1 } # Add the function body to the vector function_body <- c(function_body, body) } } # If no function definitions were found, create a data frame with NA values if (length(function_name) == 0) { data_frame <- data.frame( main_script = script_name, function_name = NA, arguments = NA, function_body = NA ) } else { # Create a dataframe data_frame <- data.frame( main_script = script_name, function_name = function_name, arguments = arguments, function_body = function_body ) } # Return the dataframe return(data_frame) }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/retrieve_function_calls.R
#' Retrieve functions and packages #' #' Retrieves functions and their corresponding packages used in a given script. #' #' @param path The complete path of the script. #' @return Used_functions #' #' @export retrieve_functions_and_packages <- function(path) { tryCatch(tmp <- utils::getParseData(parse(path, keep.source = TRUE)), error = function(e) message(as.character(e)) ) ## Retrieve all functions in the script. nms <- tmp$text[which(tmp$token == "SYMBOL_FUNCTION_CALL")] if (length(nms) > 0) { df_tmp <- data.frame(nms = nms, filename = path) funs <- unique(sort(as.character(df_tmp$nms))) src <- paste(as.vector(sapply(funs, utils::find))) Used_functions <- data.frame(nms = funs, src = src, filename = path) return(Used_functions) } }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/retrieve_functions_and_packages.R
#' Retrieve packages that are loaded in a script #' #' @param script_name The path to the R script #' #' @return dataframe #' @export retrieve_package_usage <- function(script_name) { # Read the script file file <- readLines(script_name) # Initialize empty vectors to hold package names and call types package_name <- character() call_type <- character() line_number <- integer() conditional_usage <- logical() commented_out <- logical() # Patterns for package calls patterns <- list( library = "\\blibrary\\((\"[^\"]+\"|'[^']+')\\)", require = "\\brequire\\((\"[^\"]+\"|'[^']+')\\)", install_packages = "install\\.packages\\((\"[^\"]+\"|'[^']+')\\)" ) # Iterate over each line in the script file for (i in seq_along(file)) { line <- file[i] # Check each type of package call for (type in names(patterns)) { pattern <- patterns[[type]] matches <- stringr::str_extract(line, pattern = pattern) # If a match is found if (!is.na(matches)) { # Extract the package name and remove surrounding quotes pkg_name <- gsub('^"|"$', "", stringr::str_extract(matches, '(?<=")[^"]+(?=")|(?<=\')[^\']+(?=\')')) # Store the package name and call type package_name <- c(package_name, pkg_name) call_type <- c(call_type, type) line_number <- c(line_number, i) # Check for conditional usage conditional_usage <- c(conditional_usage, any(grepl("\\b(if|else|switch)\\b", file[max(1, i - 5):i]))) # Check if the package usage is commented out commented_out <- c(commented_out, grepl("^#", line)) } } } # If no package calls were found, create a data frame with NA values if (length(package_name) == 0) { data_frame <- data.frame( main_script = script_name, package_name = NA, call_type = NA, line_number = NA, conditional_usage = NA, commented_out = NA ) } else { # Create a dataframe data_frame <- data.frame( main_script = script_name, package_name = package_name, call_type = call_type, line_number = line_number, conditional_usage = conditional_usage, commented_out = commented_out ) } # Return the dataframe return(data_frame) }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/retrieve_package_usage.R
# Retrieves all sourced scripts within a main Rscript #' retrieve_sourced_scripts #' #' @param script_name The main script to search #' #' @return dataframe #' @export #' retrieve_sourced_scripts <- function(script_name) { # Read the script file file <- readLines(script_name) # Initialize empty vectors to hold sourced scripts and comment status sourced_script <- character() line_number <- integer() conditional_sourcing <- logical() loop_sourcing <- logical() repeated_sourcing <- logical() script_exists <- logical() commented_out <- logical() # Iterate over each line in the script file for (i in seq_along(file)) { line <- file[i] # Extract the sourced file name and parameters using regex pattern <- stringr::str_extract(line, pattern = "(?<=source\\(\")[^\"]+\\.R(?=\"\\))" ) # If a source call is found if (!is.na(pattern)) { sourced_script <- c(sourced_script, pattern) # Check if the source call is commented out line_number <- c(line_number, i) # Check for conditional sourcing and loop sourcing conditional_sourcing <- c(conditional_sourcing, any(grepl("\\b(if|else|switch)\\b", file[max(1, i - 5):i]))) loop_sourcing <- c(loop_sourcing, any(grepl("\\b(for|while|repeat)\\b", file[max(1, i - 5):i]))) # Check if the sourced script exists script_exists <- c(script_exists, file.exists(pattern)) # Check if the source call is commented out commented_out <- c(commented_out, startsWith(trimws(line), "#")) } } # Check for repeated sourcing repeated_sourcing <- duplicated(sourced_script) # If no sourced scripts were found, create a data frame with NA values if (length(sourced_script) == 0) { data_frame <- data.frame( main_script = script_name, sourced_script = NA, line_number = NA, commented_out = NA, conditional_sourcing = NA, loop_sourcing = NA, repeated_sourcing = NA, script_exists = NA ) } else { # Create a dataframe data_frame <- data.frame( main_script = script_name, sourced_script = sourced_script, line_number = line_number, commented_out = commented_out, conditional_sourcing = conditional_sourcing, loop_sourcing = loop_sourcing, repeated_sourcing = repeated_sourcing, script_exists = script_exists ) } # Return the dataframe return(data_frame) }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/retrieve_sourced_scripts.R
# Retrieves all assigned string objects within a Rscript #' retrieve_string_assignments #' #' @param script_name The script to search objects in #' #' @return dataframe #' @export #' retrieve_string_assignments <- function(script_name) { # Read the script file file <- readLines(script_name) # Initialize empty vectors to hold object names and their assigned strings object_name <- character() string <- character() # Iterate over each line in the script file for (line in file) { # Extract the object names and strings using regex pattern <- stringr::str_match(line, pattern = "(\\w+)\\s*<-\\s*\"(.*)\"" ) # If a string assignment is found if (!is.na(pattern[1, 1])) { object_name <- c(object_name, pattern[1, 2]) string <- c(string, pattern[1, 3]) } } # If no string assignments were found, create a data frame with NA values if (length(object_name) == 0) { data_frame <- data.frame( main_script = script_name, object_name = NA, string = NA ) } else { # Create a dataframe data_frame <- data.frame( main_script = script_name, object_name = object_name, string = string ) } # Return the dataframe return(data_frame) }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/retrieve_string_assignments.R
#' Return Assertion Messages #' #' This function returns a message indicating whether an assertion test has passed or failed. #' An "assertion collection" from the checkmate package must be provided. The message can be returned as an error or a warning. #' For some assertions, only warnings are allowed, as an error would stop the script from running. #' This is done for the following assertions: percentage missing values, duplicates, subset, and set_equal. #' #' @param collection An object with the class "AssertCollection". #' @param collection_name The name of the collection. This name is mentioned in the messages. #' @param fail "stop" or "warning". If the assertions fail, an error is returned and the script output is stopped. If "warning", only a warning is returned. #' @param silent If FALSE (default), the success message is printed in the console. If TRUE, it is not shown. #' @param output_map A map, like 1. Read data, where the file is stored. #' #' @return The message indicating whether the assertion test has passed or failed. #' @export return_assertions_message <- function(collection, collection_name, fail = "stop", silent = FALSE, output_map = NULL) { stopifnot(class(collection) == "AssertCollection") if (collection$isEmpty()) { if (silent) { return(invisible(paste(collection_name, "Assertions PASSED", sep = ": "))) } else { return(paste(collection_name, "Assertions PASSED", sep = ": ")) } } else { message_count <- length(collection$getMessages()) assertion_title <- paste(collection_name, ": ", message_count, " Assertion", if (message_count == 1) { "" } else { "s" }, " FAILED", sep = "" ) warning_messages <- c() error_messages <- c() for (message in collection$getMessages()) { if (grepl("Must be a subset of", message) | grepl("Must be equal to set", message) | grepl("Allowed % NAs is", message) | grepl("Number of duplicate rows", message)) { warning_messages <- c(warning_messages, message) } else { error_messages <- c(error_messages, message) } } assertion_messages <- paste( cli::style_bold(paste0(1:message_count, ".")), collection$getMessages(), collapse = "\n" ) return_message <- paste(cli::style_bold(cli::col_red(assertion_title)), cli::col_cyan(assertion_messages), sep = "\n" ) message(return_message) if (fail == "stop") { if (length(error_messages) > 0) { stop(return_message) } else { return(warning(return_message)) } } else if (fail == "warning") { return(warning(return_message)) } } } #' Check for columns with only NA values #' #' This function checks if there are any columns in the provided dataframe that contain only NA values. #' If such columns exist, their names are added to the provided collection. #' #' @param df A dataframe. #' @param collection A list to store the names of the columns with only NA values. #' @return The updated collection. #' @examples #' # Create a dataframe with some columns containing only NA values #' df <- data.frame(a = c(1, NA, 3), b = c(NA, NA, NA), c = c(4, 5, 6)) #' collection <- checkmate::makeAssertCollection() #' check_na_columns(df, collection) #' @export check_na_columns <- function(df, collection) { p_na <- variable <- NULL na_percentage <- data.frame(p_na = round(100 * sapply(df, function(x) sum(is.na(x))) / nrow(df), 2)) na_percentage$variable <- rownames(na_percentage) rownames(na_percentage) <- NULL if (any(na_percentage$p_na == 100)) { columns <- na_percentage %>% dplyr::filter(p_na == 100) %>% dplyr::select(variable) %>% unlist() %>% toString() collection$push(paste("The following columns contain 100% NA's:", columns)) } return(collection) } #' Check for Columns with Only 0s #' #' This function checks if there are any columns in the provided dataframe that contain only 0 values. #' If such columns exist, their names are added to the provided collection. #' #' @param dataframe A dataframe. #' @param collection A list to store the names of the columns with only 0 values. #' @return The updated collection. #' @examples #' # Create a dataframe with some columns containing only 0 values #' dataframe <- data.frame(a = c(0, 0, 0), b = c(1, 2, 3), c = c(0, 0, 0)) #' collection <- checkmate::makeAssertCollection() #' check_zero_columns(dataframe, collection) #' @export check_zero_columns <- function(dataframe, collection) { percentage_zeros <- variable <- p_zeros <- NULL ## Create dataframe with percentage 0 per column df_zeros <- data.frame(p_zeros = round(100 * sapply( dataframe, function(x) sum(x == 0, na.rm = T) ) / nrow(dataframe), 2)) df_zeros$variable <- rownames(df_zeros) rownames(df_zeros) <- NULL if (any(df_zeros$p_zeros == 100)) { columns <- df_zeros %>% dplyr::filter(p_zeros == 100) %>% dplyr::select(variable) %>% unlist() %>% toString() collection$push(paste("The following columns contain 100% 0s:", columns)) } return(collection) } #' Check for Non-Zero Rows #' #' This function checks if there are more than 0 rows in the provided dataframe. #' If there are 0 rows, a message is added to the provided collection. #' #' @param dataframe A dataframe. #' @param collection A list to store the message if there are 0 rows. #' @return The updated collection. #' @examples #' # Create an empty dataframe #' dataframe <- data.frame() #' collection <- checkmate::makeAssertCollection() #' check_non_zero_rows(dataframe, collection) #' @export check_non_zero_rows <- function(dataframe, collection) { if (nrow(dataframe) <= 0) { collection$push("The dataset contains 0 rows") } return(collection) }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/return_assertions_message.R
#' Detect string in file #' #' @param file Path to file. #' @param pattern Pattern to match. #' @param only_comments default FALSE. Whether to only search in commented lines. #' @param collapse default: FALSE: search file line by line. #' If true, then pattern is search in the entire file at once after collapsing. #' (only_comments does not work when collapse is set to TRUE) #' @return Boolean whether pattern exists in file. #' @export str_detect_in_file <- function(file, pattern, only_comments = FALSE, collapse = FALSE) { Lines <- readLines(file, warn = FALSE) if (!collapse) { if (only_comments) { Search_line <- stringr::str_detect(Lines, "^\\s*#") } else { Search_line <- T } Result <- any(stringr::str_detect(Lines[Search_line], pattern = pattern)) } else { Lines_collapsed <- paste(c(Lines, ""), collapse = "\n") Result <- stringr::str_detect(Lines_collapsed, pattern = pattern) } if (is.na(Result)) { Result <- FALSE } return(Result) }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/str_detect_in_file.R
#' Test all equal #' #' Test whether all values in a vector are equal. #' @param x Vector to test. #' @param na.rm default: FALSE. exclude NAs from the test. #' @return Boolean result of the test #' @examples #' test_all_equal(c(5, 5, 5)) #' #' test_all_equal(c(5, 6, 3)) #' #' @family tests #' @export test_all_equal <- function(x, na.rm = FALSE) { if (!na.rm) { return(length(unique(x)) <= 1) } else { return(length(unique(x[!is.na(x)])) <= 1) } }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/test_all_equal.R
#' unique id #' #' Check if parsed variable is a unique identifier. #' This function was adapted from: #' Source: https://edwinth.github.io/blog/unique_id/ #' @param x vector or dataframe. #' @importFrom magrittr %>% #' @param ... optional variables, e.g. name of column or a vector of names. #' @return Boolean whether variable is a unique identifier. #' @examples #' unique_id(iris, Species) #' #' mtcars$name <- rownames(mtcars) #' unique_id(mtcars, name) #' #' @export unique_id <- function(x, ...) { id_set <- x %>% dplyr::select(...) id_set_dist <- id_set %>% dplyr::distinct() print(id_set_dist) if (nrow(id_set) == nrow(id_set_dist)) { return(TRUE) } else { return(FALSE) } }
/scratch/gouwar.j/cran-all/cranData/vvauditor/R/unique_id.R
## ----include = FALSE---------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----setup-------------------------------------------------------------------- library(vvauditor) ## ----summary, cols.print=5---------------------------------------------------- summary_table <- create_dataset_summary_table(mtcars) summary_table ## ----get_first_element_class-------------------------------------------------- ## Example usage get_first_element_class(mtcars$mpg) # "numeric" ## ----min_max------------------------------------------------------------------ # Example usage find_minimum_value(mtcars$hp) # Minimum horsepower find_maximum_value(mtcars$disp) # Maximum displacement ## ----unique------------------------------------------------------------------- # Example usage is_unique_column("cyl", mtcars) # Are cylinder numbers unique? ## ----distribution------------------------------------------------------------- # Example usage get_distribution_statistics(mtcars$wt) # Distribution statistics for weight ## ----percentages-------------------------------------------------------------- # Example usage calculate_category_percentages(mtcars$gear) # Category percentages for gears
/scratch/gouwar.j/cran-all/cranData/vvauditor/inst/doc/dataset-summary.R
--- title: "Creating Dataset Summary Tables" output: html_document: df_print: paged vignette: > %\VignetteIndexEntry{dataset-summary} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` # Overview The `create_dataset_summary_table` function is a powerful tool for data analysts who need to quickly assess the structure and content of their datasets. This vignette will guide you through the process of using this function and its auxiliary functions to generate a comprehensive summary of any dataframe. # Getting Started First, let's load the necessary libraries and our custom package: ```{r setup} library(vvauditor) ``` # Creating The Summary Table The primary function, `create_dataset_summary_table`, generates a summary statistics table for a given dataframe. Let's use the built-in mtcars dataset to see how it works: ```{r summary, cols.print=5} summary_table <- create_dataset_summary_table(mtcars) summary_table ``` The resulting table provides detailed information about each column, such as the data type, missing value percentage, range of values, and more. # Helper Functions The create_dataset_summary_table function relies on several helper functions to perform specific tasks: - `get_first_element_class`: Determines the class of the first element in a vector. - `find_minimum_value`: Locates the minimum numeric value in a vector. - `find_maximum_value`: Finds the maximum numeric value in a vector. - `is_unique_column`: Checks whether a column contains unique values. - `get_distribution_statistics`: Computes distribution statistics for numeric vectors. - `calculate_category_percentages`: Calculates the percentage of categories in a data vector. Each of these functions plays a crucial role in constructing the final summary table. We will explore each one in more detail in the following sections. ## get_first_element_class This function helps identify the data type of each column in the dataframe: ```{r get_first_element_class} ## Example usage get_first_element_class(mtcars$mpg) # "numeric" ``` ## find_minimum_value and find_maximum_value These functions assist in determining the range of values for numeric columns: ```{r min_max} # Example usage find_minimum_value(mtcars$hp) # Minimum horsepower find_maximum_value(mtcars$disp) # Maximum displacement ``` ## is_unique_column With this function, you can easily check for uniqueness in a particular column: ```{r unique} # Example usage is_unique_column("cyl", mtcars) # Are cylinder numbers unique? ``` ## get_distribution_statistics This function provides descriptive statistics for numeric columns: ```{r distribution} # Example usage get_distribution_statistics(mtcars$wt) # Distribution statistics for weight ``` ## calculate_category_percentages Lastly, this function calculates the percentage breakdown of categories in a data vector: ```{r percentages} # Example usage calculate_category_percentages(mtcars$gear) # Category percentages for gears ``` # Conclusion The `create_dataset_summary_table` function and its companion functions offer a convenient way to gain immediate insights into the structure and content of your data. By understanding and utilizing these tools, you can expedite your data exploration process and make more informed decisions during your analysis.
/scratch/gouwar.j/cran-all/cranData/vvauditor/inst/doc/dataset-summary.Rmd
--- title: "Creating Dataset Summary Tables" output: html_document: df_print: paged vignette: > %\VignetteIndexEntry{dataset-summary} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` # Overview The `create_dataset_summary_table` function is a powerful tool for data analysts who need to quickly assess the structure and content of their datasets. This vignette will guide you through the process of using this function and its auxiliary functions to generate a comprehensive summary of any dataframe. # Getting Started First, let's load the necessary libraries and our custom package: ```{r setup} library(vvauditor) ``` # Creating The Summary Table The primary function, `create_dataset_summary_table`, generates a summary statistics table for a given dataframe. Let's use the built-in mtcars dataset to see how it works: ```{r summary, cols.print=5} summary_table <- create_dataset_summary_table(mtcars) summary_table ``` The resulting table provides detailed information about each column, such as the data type, missing value percentage, range of values, and more. # Helper Functions The create_dataset_summary_table function relies on several helper functions to perform specific tasks: - `get_first_element_class`: Determines the class of the first element in a vector. - `find_minimum_value`: Locates the minimum numeric value in a vector. - `find_maximum_value`: Finds the maximum numeric value in a vector. - `is_unique_column`: Checks whether a column contains unique values. - `get_distribution_statistics`: Computes distribution statistics for numeric vectors. - `calculate_category_percentages`: Calculates the percentage of categories in a data vector. Each of these functions plays a crucial role in constructing the final summary table. We will explore each one in more detail in the following sections. ## get_first_element_class This function helps identify the data type of each column in the dataframe: ```{r get_first_element_class} ## Example usage get_first_element_class(mtcars$mpg) # "numeric" ``` ## find_minimum_value and find_maximum_value These functions assist in determining the range of values for numeric columns: ```{r min_max} # Example usage find_minimum_value(mtcars$hp) # Minimum horsepower find_maximum_value(mtcars$disp) # Maximum displacement ``` ## is_unique_column With this function, you can easily check for uniqueness in a particular column: ```{r unique} # Example usage is_unique_column("cyl", mtcars) # Are cylinder numbers unique? ``` ## get_distribution_statistics This function provides descriptive statistics for numeric columns: ```{r distribution} # Example usage get_distribution_statistics(mtcars$wt) # Distribution statistics for weight ``` ## calculate_category_percentages Lastly, this function calculates the percentage breakdown of categories in a data vector: ```{r percentages} # Example usage calculate_category_percentages(mtcars$gear) # Category percentages for gears ``` # Conclusion The `create_dataset_summary_table` function and its companion functions offer a convenient way to gain immediate insights into the structure and content of your data. By understanding and utilizing these tools, you can expedite your data exploration process and make more informed decisions during your analysis.
/scratch/gouwar.j/cran-all/cranData/vvauditor/vignettes/dataset-summary.Rmd
#' Authenticate with Canvas LMS API #' #' Handles authentication with the Canvas LMS API using the provided API key and base URL. #' #' @param api_key The API key for authenticating with the Canvas LMS API. #' @param base_url The base URL of the Canvas instance. #' #' @return A list containing the authenticated 'api_key' and 'base_url'. #' @export #' @examples #' \dontrun{ #' # Authenticate with the Canvas LMS API #' api_key <- "your_api_key" #' base_url <- "https://canvas.example.com" #' canvas <- canvas_authenticate(api_key, base_url) #' } canvas_authenticate <- function(api_key, base_url) { # Create a canvas object to store the API key and base URL canvas <- list(api_key = api_key, base_url = base_url) # Check if the base URL ends with a trailing slash and remove it if present if (substr(canvas$base_url, nchar(canvas$base_url), nchar(canvas$base_url)) == "/") { canvas$base_url <- substr(canvas$base_url, 1, nchar(canvas$base_url) - 1) } # Verify authentication by making a test request test_url <- paste0(canvas$base_url, "/api/v1/users/self") response <- httr::GET(test_url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Authentication failed. Please check your API key and base URL.") } # Return the canvas object return(canvas) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/authenticate.R
#' Create an Assignment Group in Canvas LMS #' #' Creates a new assignment group in a specific course using the Canvas LMS API. #' #' @param canvas A list containing the 'api_key' and 'base_url' for authentication. #' @param course_id The ID of the course in which to create the assignment group. #' @param group_name The name of the assignment group. #' @param group_position The position of the assignment group in the course (optional). #' #' @return A confirmation message that the assignment group has been created. #' @export #' create_assignment_group <- function(canvas, course_id, group_name, group_position = NULL) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/courses/", course_id, "/assignment_groups") # Create the request payload payload <- list( "name" = group_name, "position" = group_position ) # Make the API request response <- httr::POST(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key)), body = payload, encode = "json") # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to create assignment group. Please check your authentication and API endpoint.") } # Return a confirmation message return("The assignment group has been created.") }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/create_assignment_group.R
#' Create a data lake for a course. #' #' This function retrieves data from various endpoints for a specific course in the Canvas LMS API #' and stores the data as JSON files in a specified storage location. #' #' @param canvas An object containing the Canvas API key and base URL, obtained through the `canvas_authenticate` function. #' @param course_id The ID of the course for which to create the data lake. #' @param storage_location The path to the storage location where the data files will be saved. #' @return NULL. #' #' @export #' @note This function retrieves data from various endpoints. Access to certain endpoints may require specific roles. create_course_datalake <- function(canvas, course_id, storage_location) { # Check if the storage location exists and create it if not if (!dir.exists(storage_location)) { dir.create(storage_location, recursive = TRUE) } # Define the list of endpoints to retrieve data from endpoints <- list( "details" = "/api/v1/courses/{course_id}", "analytics" = "/api/v1/courses/{course_id}/analytics", "assignments" = "/api/v1/courses/{course_id}/assignments", "assignment_groups" = "/api/v1/courses/{course_id}/assignment_groups", "conferences" = "/api/v1/courses/{course_id}/conferences", "discussion_topics" = "/api/v1/courses/{course_id}/discussion_topics", "files" = "/api/v1/courses/{course_id}/files", "folders" = "/api/v1/courses/{course_id}/folders", "modules" = "/api/v1/courses/{course_id}/modules", "module_items" = "/api/v1/courses/{course_id}/modules/items", "outcomes" = "/api/v1/courses/{course_id}/outcomes", "pages" = "/api/v1/courses/{course_id}/pages", "quizzes" = "/api/v1/courses/{course_id}/quizzes", "rubrics" = "/api/v1/courses/{course_id}/rubrics", "sections" = "/api/v1/courses/{course_id}/sections", "assignments_for_grade_export" = "/api/v1/courses/{course_id}/assignments/for_grade_export", "enrollments" = "/api/v1/courses/{course_id}/enrollments", "student_enrollments" = "/api/v1/courses/{course_id}/enrollments?type[]=student", "teacher_enrollments" = "/api/v1/courses/{course_id}/enrollments?type[]=teacher", "ta_enrollments" = "/api/v1/courses/{course_id}/enrollments?type[]=ta", "observer_enrollments" = "/api/v1/courses/{course_id}/enrollments?type[]=observer", "admin_enrollments" = "/api/v1/courses/{course_id}/enrollments?type[]=admin", "collaborations" = "/api/v1/courses/{course_id}/collaborations", "users" = "/api/v1/courses/{course_id}/users", "course_score_and_grade_export" = "/api/v1/courses/{course_id}/score_and_grade_export", "course_settings" = "/api/v1/courses/{course_id}/settings", "blueprint_templates" = "/api/v1/courses/{course_id}/blueprint_templates", "blueprint_subscriptions" = "/api/v1/courses/{course_id}/blueprint_subscriptions", "blueprint_migrations" = "/api/v1/courses/{course_id}/blueprint_migrations", "blueprint_import" = "/api/v1/courses/{course_id}/blueprint_import", "blueprint_exports" = "/api/v1/courses/{course_id}/blueprint_exports", "storage_quota_used" = "/api/v1/courses/{course_id}/storage_quota_used", "tabs" = "/api/v1/courses/{course_id}/tabs", "usage_rights" = "/api/v1/courses/{course_id}/usage_rights", "account_notifications" = "/api/v1/courses/{course_id}/account_notifications", "blueprint_restricted_attachments" = "/api/v1/courses/{course_id}/blueprint_restricted_attachments", "usage_rights_information" = "/api/v1/courses/{course_id}/usage_rights_information", "default_view" = "/api/v1/courses/{course_id}/default_view", "calendar_events" = "/api/v1/courses/{course_id}/calendar_events", "calendars" = "/api/v1/courses/{course_id}/calendars", "appointment_groups" = "/api/v1/courses/{course_id}/appointment_groups", "external_feeds" = "/api/v1/courses/{course_id}/external_feeds", "rubric_associations" = "/api/v1/courses/{course_id}/rubric_associations", "content_exports" = "/api/v1/courses/{course_id}/content_exports", "content_imports" = "/api/v1/courses/{course_id}/content_imports", "content_migration" = "/api/v1/courses/{course_id}/content_migrations", "blueprint_course_associations" = "/api/v1/courses/{course_id}/blueprint_course_associations", "blueprint_restrictions" = "/api/v1/courses/{course_id}/blueprint_restrictions", "calendar_events_feed" = "/api/v1/courses/{course_id}/calendar_events/feed", "calendar_event_reservations" = "/api/v1/courses/{course_id}/calendar_event_reservations", "calendar_events_user" = "/api/v1/courses/{course_id}/calendar_events/user" ) # Iterate through the endpoints and retrieve data for (endpoint in names(endpoints)) { # Construct the API endpoint URL endpoint_url <- gsub("\\{course_id\\}", course_id, endpoints[[endpoint]]) url <- paste0(canvas$base_url, endpoint_url) # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { message(paste("Failed to retrieve data from endpoint:", endpoint), "\n") next } # Parse the response as JSON data <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) # Define the file path to store the data file_path <- file.path(storage_location, paste0(endpoint, ".json")) # Write the data to file in JSON format jsonlite::write_json(data, file_path) message(paste("Data from endpoint", endpoint, "saved to", file_path), "\n") } message("Course data lake created successfully!\n") }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/create_course_datalake.R
#' Create a Course Section in Canvas LMS #' #' Creates a new course section in a specific course using the Canvas LMS API. #' #' @param canvas A list containing the 'api_key' and 'base_url' for authentication. #' @param course_id The ID of the course in which to create the section. #' @param section_name The name of the section. #' @param section_start_date (Optional) The start date of the section. #' @param section_end_date (Optional) The end date of the section. #' #' @return A confirmation message that the section has been created. #' @export #' create_course_section <- function(canvas, course_id, section_name, section_start_date = NULL, section_end_date = NULL) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/courses/", course_id, "/sections") # Create the request payload payload <- list( "course_section" = list( "name" = section_name, "start_at" = section_start_date, "end_at" = section_end_date ) ) # Make the API request response <- httr::POST(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key)), body = payload, encode = "json") # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to create course section. Please check your authentication and API endpoint.") } # Return a confirmation message return("The course section has been created.") }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/create_course_section.R
#' Create a Folder in Canvas LMS #' #' Creates a new folder in a specific course using the Canvas LMS API. #' #' @param canvas A list containing the 'api_key' and 'base_url' for authentication. #' @param course_id The ID of the course in which to create the folder. #' @param folder_name The name of the folder. #' @param parent_folder_id (Optional) The ID of the parent folder in which to create the folder. #' #' @return A confirmation message that the folder has been created. #' @export #' create_folder <- function(canvas, course_id, folder_name, parent_folder_id = NULL) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/courses/", course_id, "/folders") # Create the request payload payload <- list( "name" = folder_name, "parent_folder_id" = parent_folder_id ) # Make the API request response <- httr::POST(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key)), body = payload, encode = "json") # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to create folder. Please check your authentication and API endpoint.") } # Return a confirmation message return("The folder has been created.") }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/create_folder.R
#' Create a Group Category in Canvas LMS #' #' Creates a new group category in a specific course using the Canvas LMS API. #' #' @param canvas A list containing the 'api_key' and 'base_url' for authentication. #' @param course_id The ID of the course in which to create the group category. #' @param category_name The name of the group category. #' @param allow_self_signup (Optional) Whether to allow self-signup for groups in the category. Defaults to FALSE. #' #' @return A confirmation message that the group category has been created. #' @export #' create_group_category <- function(canvas, course_id, category_name, allow_self_signup = FALSE) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/courses/", course_id, "/group_categories") # Create the request payload payload <- list( "name" = category_name, "self_signup" = allow_self_signup ) # Make the API request response <- httr::POST(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key)), body = payload, encode = "json") # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to create group category. Please check your authentication and API endpoint.") } # Return a confirmation message return("The group category has been created.") }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/create_group_category.R
#' Create a Page in Canvas LMS #' #' Creates a new page in a specific course using the Canvas LMS API. #' #' @param canvas A list containing the 'api_key' and 'base_url' for authentication. #' @param course_id The ID of the course in which to create the page. #' @param page_title The title of the page. #' @param page_body The body/content of the page. #' @param published (Optional) Whether the page should be published. Defaults to FALSE. #' #' @return A confirmation message that the page has been created. #' @export #' create_page <- function(canvas, course_id, page_title, page_body, published = FALSE) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/courses/", course_id, "/pages") # Create the request payload payload <- list( "wiki_page" = list( "title" = page_title, "body" = page_body, "published" = published ) ) # Make the API request response <- httr::POST(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key)), body = payload, encode = "json") # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to create page. Please check your authentication and API endpoint.") } # Return a confirmation message return("The page has been created.") }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/create_page.R
#' Downloads a file from a given URL. #' #' This function downloads a file from a specified URL and saves it locally. #' #' @param canvas An object containing the Canvas API key and base URL, obtained through the `canvas_authenticate` function. #' @param file_url The URL of the file to download. #' @param download_path The path where the file should be downloaded. #' #' @return The path of the downloaded file. #' @export #' @examples #' \dontrun{ #' # Download a file from a given URL #' canvas <- canvas_authenticate(api_key, base_url) #' file_url <- "https://example.com/file.pdf" #' download_path <- "path/to/save/file.pdf" #' file_path <- download_course_file(canvas, file_url, download_path) #' } #' @importFrom utils download.file download_course_file <- function(canvas, file_url, download_path) { # Get the filename from the URL response <- httr::GET(file_url) # Extract filename including extension from the response url filename <- stringr::str_extract(response$url, paste0("\\b\\w+\\.(?i)(pdf|txt|csv|ppt|pptx)\\b")) # Set the path for the downloaded file file_path <- file.path(download_path, filename) # Download the file download_result <- tryCatch( { download.file(file_url, destfile = file_path, mode = "wb") file_path }, error = function(e) { stop(paste("Failed to download file from URL:", file_url)) } ) return(download_result) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/download_course_file.R
#' Get a list of accounts from the Canvas LMS API #' #' Retrieves a paginated list of accounts that the current user can view or manage. #' #' @param canvas A list containing the 'api_key' and 'base_url' for authentication. #' @param include A vector of additional information to include. Default is NULL. #' @param per_page Number of accounts to retrieve per page. Default is 100. #' #' @return A list of accounts retrieved from the Canvas LMS API. #' @export get_accounts <- function(canvas, include = NULL, per_page = 100) { # Define the legal values for the 'include' parameter legal_values <- c("lti_guid", "registration_settings", "services") # Check that the 'include' parameter uses legal values if (!is.null(include)) { if (any(!include %in% legal_values)) { stop("The 'include' parameter must use legal values: 'lti_guid', 'registration_settings', 'services'.") } } # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/accounts?per_page=", per_page) # Add the 'include' parameter to the URL if it's not NULL if (!is.null(include)) { url <- paste0(url, "&include[]=", paste(include, collapse = "&include[]=")) } # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve the list of accounts. Please check your authentication and API endpoint.") } # Parse the response as JSON accounts <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) # Return the list of accounts return(accounts) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_accounts.R
#' Retrieves a paginated list of all courses visible in the public index. #' #' This function retrieves a paginated list of all courses visible in the public index #' using the Canvas LMS API. #' *NOTE* This function might take a while to finish. #' @param canvas An object containing the Canvas API key and base URL, obtained through the `canvas_authenticate` function. #' @param per_page (Optional) The number of courses to retrieve per page of results (default is 100). #' #' @return A data frame of courses visible in the public index. #' @export get_all_courses <- function(canvas, per_page = 100) { # Initialize an empty data frame to store the courses all_courses <- data.frame() # Start with the first page page <- 1 # Loop until all pages have been fetched while (TRUE) { # Construct the API endpoint URL for the current page url <- paste0(canvas$base_url, "/api/v1/search/all_courses?per_page=", per_page, "&page=", page) # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve all courses. Please check your authentication and API endpoint.") } # Parse the response as JSON courses <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) # Append the courses to the accumulated data frame all_courses <- dplyr::bind_rows(all_courses, courses) # Print progress message message("Fetched", nrow(courses), "courses from page", page, "\n") # Increment the page counter page <- page + 1 # Break the loop if there are no more courses if (length(courses) == 0) { break } } # Return the data frame of all courses return(all_courses) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_all_courses.R
#' Get course-level assignment data from the Canvas LMS API #' #' Retrieves the course-level assignment data for a specific course from the Canvas LMS API. #' #' @param canvas A list containing the 'api_key' and 'base_url' for authentication. #' @param course_id The ID of the course for which to retrieve the assignment data. #' @param per_page Number of assignment data to retrieve per page. Default is 100. #' #' @return A list of assignment data retrieved from the Canvas LMS API. #' @export get_assignment_data <- function(canvas, course_id, per_page = 100) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/courses/", course_id, "/analytics/assignments?per_page=", per_page) # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve assignment data. Please check your authentication and API endpoint.") } # Parse the response as JSON assignment_data <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) # Return the assignment data return(assignment_data) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_assignment_data.R
#' Get Assignment Details from Canvas LMS API #' #' Retrieves detailed information about a specific assignment from the Canvas LMS API. #' #' @param canvas A list containing the 'api_key' and 'base_url' for authentication. #' @param course_id The ID of the course in which the assignment resides. #' @param assignment_id The ID of the assignment for which to retrieve the details. #' #' @return A dataframe containing the detailed information about the assignment. #' @export #' get_assignment_details <- function(canvas, course_id, assignment_id) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/courses/", course_id, "/assignments/", assignment_id) # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve assignment details. Please check your authentication and API endpoint.") } # Parse the response as JSON assignment_details <- httr::content(response, "text", encoding = "UTF-8") # Return the assignment details as a list return(assignment_details) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_assignment_details.R
#' Lists assignment submissions for a course. #' #' This function retrieves a list of assignment submissions for a specific course in the Canvas LMS API. #' #' @param canvas An object containing the Canvas API key and base URL, obtained through the `canvas_authenticate` function. #' @param course_id The ID of the course for which to list assignment submissions. #' @param assignment_id (Optional) The ID of a specific assignment for which to list submissions. #' @param per_page (Optional) The number of submissions to retrieve per page of results (default is 100). #' #' @return A data frame of assignment submissions for the specified course and assignment. #' @export get_assignment_submissions <- function(canvas, course_id, assignment_id = NULL, per_page = 100) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/courses/", course_id, "/students/submissions?per_page=", per_page) # Append the assignment_id if provided if (!is.null(assignment_id)) { url <- paste0(url, "&assignment_id=", assignment_id) } # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve assignment submissions. Please check your authentication and API endpoint.") } # Parse the response as JSON submissions <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) %>% tidyr::unnest(names_sep = ".") # Return the data frame of submissions return(submissions) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_assignment_submissions.R
#' Get Assignments from Canvas LMS API #' #' Fetches a list of assignments within a specific course from the Canvas LMS API. #' #' @param canvas A list containing the 'api_key' and 'base_url' for authentication. #' @param course_id The ID of the course for which to retrieve the assignments. #' #' @return A list of assignments retrieved from the Canvas LMS API. #' @export #' get_assignments <- function(canvas, course_id) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/courses/", course_id, "/assignments") # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve assignments. Please check your authentication and API endpoint.") } # Parse the response as JSON assignments <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) # Return the list of assignments return(assignments) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_assignments.R
#' Retrieves course announcements. #' #' This function retrieves a list of announcements for a specific course in the Canvas LMS API. #' #' @param canvas An object containing the Canvas API key and base URL, obtained through the `canvas_authenticate` function. #' @param course_id The ID of the course for which to retrieve announcements. #' @param per_page (Optional) The number of announcements to retrieve per page of results (default is 100). #' #' @return A data frame of course announcements. #' @export #' get_course_announcements <- function(canvas, course_id, per_page = 100) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/courses/", course_id, "/discussion_topics?only_announcements=true&per_page=", per_page) # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve course announcements. Please check your authentication and API endpoint.") } # Parse the response as JSON announcements <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) # Return the data frame of announcements return(announcements) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_course_announcements.R
#' Get Course Details from Canvas LMS API #' #' Retrieves detailed information about a specific course from the Canvas LMS API. #' #' @param canvas A list containing the 'api_key' and 'base_url' for authentication. #' @param course_id The ID of the course for which to retrieve the details. #' #' @return A dataframe containing the detailed information about the course. #' @export #' get_course_details <- function(canvas, course_id) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/courses/", course_id) # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve course details. Please check your authentication and API endpoint.") } # Parse the response as JSON and convert to a dataframe course_details <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) %>% dplyr::bind_rows() # Return the course details dataframe return(course_details) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_course_details.R
#' Retrieves the course enrollments for a course. #' #' This function retrieves the enrollments of students and other roles in a specific course in the Canvas LMS API. #' #' @param canvas An object containing the Canvas API key and base URL, obtained through the `canvas_authenticate` function. #' @param course_id The ID of the course for which to fetch the enrollments. #' @param per_page (Optional) The number of enrollments to retrieve per page of results (default is 100). #' #' @return A data frame of course enrollments for the specified course. #' @export #' get_course_enrollments <- function(canvas, course_id, per_page = 100) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/courses/", course_id, "/enrollments?per_page=", per_page) # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve course enrollments. Please check your authentication and API endpoint.") } # Parse the response as JSON enrollments <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) # Return the data frame of enrollments return(enrollments) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_course_enrollments.R
#' Retrieves a list of files within a course. #' #' This function retrieves a list of files within a specific course in the Canvas LMS API. #' #' @param canvas An object containing the Canvas API key and base URL, obtained through the `canvas_authenticate` function. #' @param course_id The ID of the course for which to fetch the files. #' @param per_page (Optional) The number of files to retrieve per page of results (default is 100). #' #' @return A data frame of files within the specified course. #' @export #' get_course_files <- function(canvas, course_id, per_page = 100) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/courses/", course_id, "/files?per_page=", per_page) # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve files. Please check your authentication and API endpoint.") } # Parse the response as JSON files <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) # Return the data frame of files return(files) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_course_files.R
#' Retrieves course folders. #' #' This function retrieves a list of folders for a specific course in the Canvas LMS API. #' #' @param canvas An object containing the Canvas API key and base URL, obtained through the `canvas_authenticate` function. #' @param course_id The ID of the course for which to retrieve folders. #' @param per_page Number of courses to retrieve per page. Default is 100. #' #' @return A data frame of course folders. #' @export #' get_course_folders <- function(canvas, course_id, per_page = 100) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/courses/", course_id, "/folders?per_page=", per_page) # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve course folders. Please check your authentication and API endpoint.") } # Parse the response as JSON folders <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) # Return the data frame of folders return(folders) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_course_folders.R
#' Retrieves the list of groups in a course. #' #' This function retrieves the list of groups in a specific course in the Canvas LMS API. #' #' @param canvas A list containing the 'api_key' and 'base_url' for authentication. #' @param course_id The ID of the course for which to fetch the groups. #' @param per_page (Optional) The number of groups to retrieve per page of results (default is 100). #' #' @return A data frame of groups in the specified course. #' @export #' get_course_groups <- function(canvas, course_id, per_page = 100) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/courses/", course_id, "/groups?per_page=", per_page) # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve course groups. Please check your authentication and API endpoint.") } # Parse the response as JSON groups <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) # Return the data frame of groups return(groups) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_course_groups.R
#' Retrieves the pages within a course. #' #' This function retrieves the pages within a specific course in the Canvas LMS API. #' #' @param canvas An object containing the Canvas API key and base URL, obtained through the `canvas_authenticate` function. #' @param course_id The ID of the course for which to fetch the pages. #' @param per_page (Optional) The number of pages to retrieve per page of results (default is 50). #' #' @return A list of pages within the specified course. #' @export #' #' @importFrom rlang .data get_course_pages <- function(canvas, course_id, per_page = 100) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/courses/", course_id, "/pages?per_page=", per_page) # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve course pages. Please check your authentication and API endpoint.") } # Parse the response as JSON pages <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) pages <- pages %>% dplyr::mutate(page_body = purrr::map_chr(.data$page_id, ~get_page_content(canvas, course_id, .x))) # Return the list of pages return(pages) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_course_pages.R
#' Get course-level participation data from Canvas LMS API #' #' Fetches the participation data for a specific course from the Canvas LMS API. #' #' @param canvas A list containing the 'api_key' and 'base_url' for authentication. #' @param course_id The ID of the course for which to retrieve the participation data. #' #' @return The participation data for the specified course retrieved from the Canvas LMS API. #' @export #' get_course_participation <- function(canvas, course_id) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/courses/", course_id, "/analytics/activity") # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve course participation data. Please check your authentication and API endpoint.") } # Parse the response as JSON participation_data <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) # Return the participation data return(participation_data) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_course_participation.R
#' Retrieves course quizzes. #' #' This function retrieves a list of quizzes for a specific course in the Canvas LMS API. #' #' @param canvas An object containing the Canvas API key and base URL, obtained through the `canvas_authenticate` function. #' @param course_id The ID of the course for which to retrieve quizzes. #' @param per_page (Optional) The number of quizzes to retrieve per page of results (default is 100). #' #' @return A data frame of course quizzes. #' @export #' get_course_quizzes <- function(canvas, course_id, per_page = 100) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/courses/", course_id, "/quizzes?per_page=", per_page) # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve course quizzes. Please check your authentication and API endpoint.") } # Parse the response as JSON quizzes <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) # Return the data frame of quizzes return(quizzes) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_course_quizzes.R
#' Retrieves course sections. #' #' This function retrieves a list of sections for a specific course in the Canvas LMS API. #' #' @param canvas An object containing the Canvas API key and base URL, obtained through the `canvas_authenticate` function. #' @param course_id The ID of the course for which to retrieve sections. #' @param per_page (Optional) The number of sections to retrieve per page of results (default is 100). #' #' @return A data frame of course sections. #' @export #' get_course_sections <- function(canvas, course_id, per_page = 100) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/courses/", course_id, "/sections?per_page=", per_page) # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve course sections. Please check your authentication and API endpoint.") } # Parse the response as JSON sections <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) # Return the data frame of sections return(sections) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_course_sections.R
#' Retrieves the list of students in a course. #' #' This function retrieves the list of students enrolled in a specific course in the Canvas LMS API. #' #' @param canvas An object containing the Canvas API key and base URL, obtained through the `canvas_authenticate` function. #' @param course_id The ID of the course for which to fetch the students. #' @param per_page (Optional) The number of students to retrieve per page of results (default is 100). #' #' @return A data frame of students enrolled in the specified course. #' @export #' get_course_students <- function(canvas, course_id, per_page = 100) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/courses/", course_id, "/students?per_page=", per_page) # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve course students. Please check your authentication and API endpoint.") } # Parse the response as JSON students <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) # Return the data frame of students return(students) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_course_students.R
#' Get Courses from Canvas LMS API #' #' Retrieves a list of courses from the Canvas LMS API. #' #' @param canvas A list containing the 'api_key' and 'base_url' for authentication. #' @param per_page Number of courses to retrieve per page. Default is 100. #' #' @return A list of courses retrieved from the Canvas LMS API. #' @export #' get_courses <- function(canvas, per_page = 100) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/courses?per_page=", per_page) # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve courses. Please check your authentication and API endpoint.") } # Parse the response as JSON courses <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) # Return the list of courses return(courses) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_courses.R
#' Get department-level grade data from the Canvas LMS API #' #' Retrieves the department-level grade data for a specific account and term from the Canvas LMS API. #' #' @param canvas A list containing the 'api_key' and 'base_url' for authentication. #' @param account_id The ID of the account for which to retrieve the grade data. #' @param type The type of courses to include in the data. Can be 'current', 'completed', or 'term'. #' @param term_id The ID of the term for which to retrieve the grade data. Only used when type is 'terms/<term_id>'. #' @param per_page Number of grade data to retrieve per page. Default is 100. #' #' @return A data frame of grade data retrieved from the Canvas LMS API. #' @export get_department_grade_data <- function(canvas, account_id, type = "current", term_id = NULL, per_page = 100) { # Define the allowed values for the 'type' parameter allowed_values <- c("current", "completed", "term") # Check that the 'type' parameter uses allowed values if (!type %in% allowed_values) { stop("The 'type' parameter must use allowed values: 'current', 'completed', 'terms/<term_id>'.") } # Construct the API endpoint URL if (type == "term>") { url <- paste0(canvas$base_url, "/api/v1/accounts/", account_id, "/analytics/terms/", term_id, "/grades?per_page=", per_page) } else { url <- paste0(canvas$base_url, "/api/v1/accounts/", account_id, "/analytics/", type, "/grades?per_page=", per_page) } # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve department-level grade data. Please check your authentication and API endpoint.") } # Parse the response as JSON grade_data <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) # Return the grade data as a data frame return(grade_data) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_department_grade_data.R
#' Get department-level participation data from the Canvas LMS API #' #' Retrieves the department-level participation data for a specific account and term from the Canvas LMS API. #' #' @param canvas A list containing the 'api_key' and 'base_url' for authentication. #' @param account_id The ID of the account for which to retrieve the participation data. #' @param type The type of courses to include in the data. Can be 'current', 'completed', or 'term'. #' @param term_id The ID of the term for which to retrieve the participation data. Only used when type is 'terms/<term_id>'. #' @param per_page Number of participation data to retrieve per page. Default is 100. #' #' @return A data frame of participation data retrieved from the Canvas LMS API. #' @export get_department_participation_data <- function(canvas, account_id, type = "current", term_id = NULL, per_page = 100) { # Define the allowed values for the 'type' parameter allowed_values <- c("current", "completed", "term") # Check that the 'type' parameter uses allowed values if (!type %in% allowed_values) { stop("The 'type' parameter must use allowed values: 'current', 'completed', 'terms'.") } # Construct the API endpoint URL if (type == "term") { url <- paste0(canvas$base_url, "/api/v1/accounts/", account_id, "/analytics/terms/", term_id, "/activity?per_page=", per_page) } else { url <- paste0(canvas$base_url, "/api/v1/accounts/", account_id, "/analytics/", type, "/activity?per_page=", per_page) } # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve department-level participation data. Please check your authentication and API endpoint.") } # Parse the response as JSON participation_data <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) # Return the participation data as a data frame return(participation_data) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_department_participation_data.R
#' Get department-level statistics from the Canvas LMS API #' #' Retrieves department-level statistics for a specific account and term from the Canvas LMS API. #' #' @param canvas A list containing the 'api_key' and 'base_url' for authentication. #' @param account_id The ID of the account for which to retrieve the statistics. #' @param type The type of courses to include in the data. Can be 'current', 'completed', or 'term'. #' @param term_id The ID of the term for which to retrieve the statistics. Only used when type is 'terms/<term_id>'. #' #' @return A list of department-level statistics retrieved from the Canvas LMS API. #' @export get_department_statistics <- function(canvas, account_id, type = "current", term_id = NULL) { # Define the allowed values for the 'type' parameter allowed_values <- c("current", "completed", "term") # Check that the 'type' parameter uses allowed values if (!type %in% allowed_values) { stop("The 'type' parameter must use allowed values: 'current', 'completed', 'term'.") } # Construct the API endpoint URL if (type == "term") { url <- paste0(canvas$base_url, "/api/v1/accounts/", account_id, "/analytics/terms/", term_id, "/statistics") } else { url <- paste0(canvas$base_url, "/api/v1/accounts/", account_id, "/analytics/", type, "/statistics") } # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve department-level statistics. Please check your authentication and API endpoint.") } # Parse the response as JSON statistics <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) # Return the statistics return(statistics) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_department_statistics.R
#' Get department-level statistics by subaccount from the Canvas LMS API #' #' Retrieves department-level statistics for a specific account and term from the Canvas LMS API. #' #' @param canvas A list containing the 'api_key' and 'base_url' for authentication. #' @param account_id The ID of the account for which to retrieve the statistics. #' @param type The type of courses to include in the data. Can be 'current', 'completed', or 'term'. #' @param term_id The ID of the term for which to retrieve the statistics. Only used when type is 'terms/<term_id>'. #' #' @return A list of department-level statistics retrieved from the Canvas LMS API. #' @export get_department_statistics_by_subaccount <- function(canvas, account_id, type = "current", term_id = NULL) { # Define the allowed values for the 'type' parameter allowed_values <- c("current", "completed", "term") # Check that the 'type' parameter uses allowed values if (!type %in% allowed_values) { stop("The 'type' parameter must use allowed values: 'current', 'completed', 'term>'.") } # Construct the API endpoint URL if (type == "term") { url <- paste0(canvas$base_url, "/api/v1/accounts/", account_id, "/analytics/terms/", term_id, "/statistics_by_subaccount") } else { url <- paste0(canvas$base_url, "/api/v1/accounts/", account_id, "/analytics/", type, "/statistics_by_subaccount") } # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve department-level statistics. Please check your authentication and API endpoint.") } # Parse the response as JSON statistics <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) # Return the statistics return(statistics) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_department_statistics_by_subaccount.R
#' Retrieves the discussion topics within a course. #' #' This function retrieves the discussion topics within a specific course in the Canvas LMS API. #' #' @param canvas An object containing the Canvas API key and base URL, obtained through the `canvas_authenticate` function. #' @param course_id The ID of the course for which to fetch the discussion topics. #' @param per_page The number of entries to show #' #' @return A list of discussion topics within the specified course. #' @export #' get_discussions <- function(canvas, course_id, per_page = 100) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/courses/", course_id, "/discussion_topics?per_page=", per_page) # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve discussion topics. Please check your authentication and API endpoint.") } # Parse the response as JSON discussions <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) # Return the list of discussion topics return(discussions) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_discussions.R
#' Get group categories for a context #' #' This function retrieves the group categories for a specific context (e.g., course) in the Canvas LMS API. #' #' @param canvas A list containing the 'api_key' and 'base_url' for authentication. #' @param course_id The ID of the course for which to retrieve the group categories. #' #' @return A data frame of group categories in the specified context. #' @export #' get_group_categories <- function(canvas, course_id) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/courses/", course_id, "/group_categories") # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve group categories. Please check your authentication and API endpoint.") } # Parse the response as JSON group_categories <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) # Return the data frame of group categories return(group_categories) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_group_categories.R
#' Get information about a single group #' #' This function retrieves information about a specific group in the Canvas LMS API. #' #' @param canvas A list containing the 'api_key' and 'base_url' for authentication. #' @param group_id The ID of the group for which to retrieve the information. #' #' @return A list containing the information about the specified group. #' @export #' get_group_info <- function(canvas, group_id) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/groups/", group_id) # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve group information. Please check your authentication and API endpoint.") } # Parse the response as JSON group_info <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) # Return the group information return(group_info) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_group_info.R
#' Get group memberships #' #' This function retrieves the memberships for a specific group in the Canvas LMS API. #' #' @param canvas A list containing the 'api_key' and 'base_url' for authentication. #' @param group_id The ID of the group for which to retrieve the memberships. #' #' @return A data frame of memberships in the specified group. #' @export #' get_group_memberships <- function(canvas, group_id) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/groups/", group_id, "/memberships") # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve group memberships. Please check your authentication and API endpoint.") } # Parse the response as JSON memberships <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) # Return the data frame of memberships return(memberships) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_group_memberships.R
#' Get users in a group #' #' This function retrieves the users in a specific group in the Canvas LMS API. #' #' @param canvas A list containing the 'api_key' and 'base_url' for authentication. #' @param group_id The ID of the group for which to retrieve the users. #' #' @return A data frame of users in the specified group. #' @export #' get_group_users <- function(canvas, group_id) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/groups/", group_id, "/users") # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve group users. Please check your authentication and API endpoint.") } # Parse the response as JSON users <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) # Return the data frame of users return(users) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_group_users.R
#' Retrieves the items within a specific module. #' #' This function retrieves the items within a specific module of a course in the Canvas LMS API. #' #' @param canvas An object containing the Canvas API key and base URL, obtained through the `canvas_authenticate` function. #' @param course_id The ID of the course containing the module. #' @param module_id The ID of the module for which to fetch the items. #' #' @return A list of items within the specified module. #' @export #' get_module_items <- function(canvas, course_id, module_id) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/courses/", course_id, "/modules/", module_id, "/items") # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve module items. Please check your authentication and API endpoint.") } # Parse the response as JSON items <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) # Return the list of items return(items) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_module_items.R
#' Retrieves the modules within a course. #' #' This function retrieves the modules within a specific course in the Canvas LMS API. #' #' @param canvas An object containing the Canvas API key and base URL, obtained through the `canvas_authenticate` function. #' @param course_id The ID of the course for which to fetch the modules. #' @param per_page The number of entries to show #' #' @return A list of modules within the specified course. #' @export #' get_modules <- function(canvas, course_id, per_page = 100) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/courses/", course_id, "/modules?per_page=", per_page) # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve modules. Please check your authentication and API endpoint.") } # Parse the response as JSON modules <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) # Return the list of modules return(modules) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_modules.R
#' Retrieves the content body of a specified page. #' #' This function retrieves the content body of a specified page within a course in the Canvas LMS API. #' #' @param canvas An object containing the Canvas API key and base URL, obtained through the `canvas_authenticate` function. #' @param course_id The ID of the course to which the page belongs. #' @param page_id The ID of the page for which to fetch the content body. #' #' @return The content body of the specified page. #' @export #' get_page_content <- function(canvas, course_id, page_id) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/courses/", course_id, "/pages/", page_id) # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve page content. Please check your authentication and API endpoint.") } # Extract the content body from the response content_body <- httr::content(response)$body # Convert the content body from HTML to plain text content_body <- htm2txt::htm2txt(content_body) # Return the content body return(content_body) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_page_content.R
#' Get student summaries for a course from Canvas LMS API #' #' Retrieves the student summaries for a specific course from the Canvas LMS API. #' #' @param canvas A list containing the 'api_key' and 'base_url' for authentication. #' @param course_id The ID of the course for which to retrieve the student summaries. #' @param per_page Number of student summaries to retrieve per page. Default is 100. #' #' @return A list of student summaries retrieved from the Canvas LMS API. #' @export #' get_student_summaries <- function(canvas, course_id, per_page = 100) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/courses/", course_id, "/analytics/student_summaries?per_page=", per_page) # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve student summaries. Please check your authentication and API endpoint.") } # Parse the response as JSON student_summaries <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) # Return the list of student summaries return(student_summaries) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_student_summaries.R
#' Get user-in-a-course-level assignment data from the Canvas LMS API #' #' Retrieves user-in-a-course-level assignment data for a specific course and student from the Canvas LMS API. #' #' @param canvas A list containing the 'api_key' and 'base_url' for authentication. #' @param course_id The ID of the course for which to retrieve the assignment data. #' @param student_id The ID of the student for which to retrieve the assignment data. #' #' @return A list of user-in-a-course-level assignment data retrieved from the Canvas LMS API. #' @export get_user_course_assignment_data <- function(canvas, course_id, student_id) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/courses/", course_id, "/analytics/users/", student_id, "/assignments") # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve user-in-a-course-level assignment data. Please check your authentication and API endpoint.") } # Parse the response as JSON assignment_data <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) # Return the assignment data return(assignment_data) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_user_course_assignment_data.R
#' Get user-in-a-course-level messaging data from the Canvas LMS API #' #' Retrieves user-in-a-course-level messaging data for a specific course and student from the Canvas LMS API. #' #' @param canvas A list containing the 'api_key' and 'base_url' for authentication. #' @param course_id The ID of the course for which to retrieve the messaging data. #' @param student_id The ID of the student for which to retrieve the messaging data. #' #' @return A list of user-in-a-course-level messaging data retrieved from the Canvas LMS API. #' @export get_user_course_messaging_data <- function(canvas, course_id, student_id) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/courses/", course_id, "/analytics/users/", student_id, "/communication") # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve user-in-a-course-level messaging data. Please check your authentication and API endpoint.") } # Parse the response as JSON messaging_data <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) # Return the messaging data return(messaging_data) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_user_course_messaging_data.R
#' Get user-in-a-course-level participation data from the Canvas LMS API #' #' Retrieves user-in-a-course-level participation data for a specific course and student from the Canvas LMS API. #' #' @param canvas A list containing the 'api_key' and 'base_url' for authentication. #' @param course_id The ID of the course for which to retrieve the participation data. #' @param student_id The ID of the student for which to retrieve the participation data. #' #' @return A list of user-in-a-course-level participation data retrieved from the Canvas LMS API. #' @export get_user_course_participation_data <- function(canvas, course_id, student_id) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/courses/", course_id, "/analytics/users/", student_id, "/activity") # Make the API request response <- httr::GET(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key))) # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to retrieve user-in-a-course-level participation data. Please check your authentication and API endpoint.") } # Parse the response as JSON participation_data <- httr::content(response, "text", encoding = "UTF-8") %>% jsonlite::fromJSON(flatten = TRUE) # Return the participation data return(participation_data) }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/get_user_course_participation_data.R
#' Post a New Discussion in Canvas LMS #' #' Creates a new discussion topic in a specific course using the Canvas LMS API. #' #' @param canvas A list containing the 'api_key' and 'base_url' for authentication. #' @param course_id The ID of the course in which to create the discussion. #' @param discussion_title The title of the discussion topic. #' @param discussion_message The initial message content of the discussion topic. #' @param discussion_is_announcement (Optional) Whether the discussion should be an announcement. Defaults to FALSE. #' #' @return A confirmation message that the discussion has been created. #' @export #' post_new_discussion <- function(canvas, course_id, discussion_title, discussion_message, discussion_is_announcement = FALSE) { # Construct the API endpoint URL url <- paste0(canvas$base_url, "/api/v1/courses/", course_id, "/discussion_topics") # Create the request payload payload <- list( "title" = discussion_title, "message" = discussion_message, "is_announcement" = discussion_is_announcement ) # Make the API request response <- httr::POST(url, httr::add_headers(Authorization = paste("Bearer", canvas$api_key)), body = payload, encode = "json") # Check the response status code if (httr::status_code(response) != 200) { stop("Failed to post new discussion. Please check your authentication and API endpoint.") } # Return a confirmation message return("The discussion has been created.") }
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/post_new_discussion.R
#' Pipe operator #' #' See \code{magrittr::\link[magrittr:pipe]{\%>\%}} for details. #' #' @name %>% #' @rdname pipe #' @keywords internal #' @export #' @importFrom magrittr %>% #' @usage lhs \%>\% rhs #' @param lhs A value or the magrittr placeholder. #' @param rhs A function call using the magrittr semantics. #' @return The result of calling `rhs(lhs)`. NULL
/scratch/gouwar.j/cran-all/cranData/vvcanvas/R/utils-pipe.R
## ---- include = FALSE--------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, eval = FALSE, comment = "#>" ) ## ----setup-------------------------------------------------------------------- # install_github("vusaverse/vvcanvas") # library(vvcanvas) ## ----authenticate------------------------------------------------------------- # # Replace the placeholders with your API key and base URL # api_key <- "YOUR_API_KEY" # base_url <- "https://your_canvas_domain.com" # # # Authenticate with the Canvas LMS API # canvas <- canvas_authenticate(api_key, base_url) # ## ----retrieve----------------------------------------------------------------- # # Fetch the dataframe of courses # courses <- get_courses(canvas) # # head(courses) # ## ----assignments-------------------------------------------------------------- # # Replace the placeholder with the desired course ID # course_id <- 12345 # # # Fetch the assignments for the course # assignments <- get_assignments(canvas, course_id) # head(assignments) #
/scratch/gouwar.j/cran-all/cranData/vvcanvas/inst/doc/getting_started.R
--- title: "Getting Started" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Getting Started} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, eval = FALSE, comment = "#>" ) ``` # Introduction The `vvcanvas` package is designed to interact with the Canvas Learning Management System (LMS) API. This vignette provides a basic guide on how to authenticate, retrieve course information, and fetch specific details using the package. # Installation To install the `vvcanvas` package, you can use the following command: ```{r setup} install_github("vusaverse/vvcanvas") library(vvcanvas) ``` # Authentication To start using the package, you need to authenticate with the Canvas LMS API using your API key and base URL. Here's an example of how to authenticate: ```{r authenticate} # Replace the placeholders with your API key and base URL api_key <- "YOUR_API_KEY" base_url <- "https://your_canvas_domain.com" # Authenticate with the Canvas LMS API canvas <- canvas_authenticate(api_key, base_url) ``` # Retrieving Course Information Once authenticated, you can retrieve course information using the get_courses function. Here's an example: ```{r retrieve} # Fetch the dataframe of courses courses <- get_courses(canvas) head(courses) ``` # Fetching Specific Details The `vvcanvas` package provides various functions to fetch specific details. For example, to retrieve the assignments within a course, you can use the get_assignments function: ```{r assignments} # Replace the placeholder with the desired course ID course_id <- 12345 # Fetch the assignments for the course assignments <- get_assignments(canvas, course_id) head(assignments) ```
/scratch/gouwar.j/cran-all/cranData/vvcanvas/inst/doc/getting_started.Rmd
## ---- include = FALSE--------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>", eval = FALSE ) ## ----setup-------------------------------------------------------------------- # library(vvcanvas) # # # # Specify the Canvas API authentication details # canvas <- list( # api_key = "YOUR_API_KEY", # base_url = "https://your_canvas_instance/" # ) # # # Retrieve all courses # courses <- get_courses(canvas) # # # Select a course (replace the index with the desired course) # course_id <- course$id[1] ## the first course in courses # ## ----get_groups--------------------------------------------------------------- # # Retrieve all groups in the selected course # groups <- get_course_groups(canvas, course_id) # # # Extract the group IDs # group_ids <- groups$id # ## ----get_members-------------------------------------------------------------- # # # Retrieve group memberships using purrr # memberships <- purrr::map_df(group_ids, ~{ # group_id <- .x # # # Retrieve the group's memberships # group_memberships <- get_group_users(canvas, group_id) # # # Extract user names from memberships # user_names <- group_memberships$name # # # Create a data frame with group memberships # group_df <- data.frame(group_id = rep(group_id, length(user_names)), # user_name = user_names, # stringsAsFactors = FALSE) # # return(group_df) # }) # #
/scratch/gouwar.j/cran-all/cranData/vvcanvas/inst/doc/groups_use_case.R
--- title: "Working with groups" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Working with groups} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", eval = FALSE ) ``` # Introduction This vignette demonstrates how to retrieve group memberships in a course using the Canvas LMS API. # Step 1: List courses ```{r setup} library(vvcanvas) # Specify the Canvas API authentication details canvas <- list( api_key = "YOUR_API_KEY", base_url = "https://your_canvas_instance/" ) # Retrieve all courses courses <- get_courses(canvas) # Select a course (replace the index with the desired course) course_id <- course$id[1] ## the first course in courses ``` # Step 2: Retrieve all groups in the course ```{r get_groups} # Retrieve all groups in the selected course groups <- get_course_groups(canvas, course_id) # Extract the group IDs group_ids <- groups$id ``` # Step 3: Retrieve group memberships ```{r get_members} # Retrieve group memberships using purrr memberships <- purrr::map_df(group_ids, ~{ group_id <- .x # Retrieve the group's memberships group_memberships <- get_group_users(canvas, group_id) # Extract user names from memberships user_names <- group_memberships$name # Create a data frame with group memberships group_df <- data.frame(group_id = rep(group_id, length(user_names)), user_name = user_names, stringsAsFactors = FALSE) return(group_df) }) ```
/scratch/gouwar.j/cran-all/cranData/vvcanvas/inst/doc/groups_use_case.Rmd
--- title: "Getting Started" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Getting Started} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, eval = FALSE, comment = "#>" ) ``` # Introduction The `vvcanvas` package is designed to interact with the Canvas Learning Management System (LMS) API. This vignette provides a basic guide on how to authenticate, retrieve course information, and fetch specific details using the package. # Installation To install the `vvcanvas` package, you can use the following command: ```{r setup} install_github("vusaverse/vvcanvas") library(vvcanvas) ``` # Authentication To start using the package, you need to authenticate with the Canvas LMS API using your API key and base URL. Here's an example of how to authenticate: ```{r authenticate} # Replace the placeholders with your API key and base URL api_key <- "YOUR_API_KEY" base_url <- "https://your_canvas_domain.com" # Authenticate with the Canvas LMS API canvas <- canvas_authenticate(api_key, base_url) ``` # Retrieving Course Information Once authenticated, you can retrieve course information using the get_courses function. Here's an example: ```{r retrieve} # Fetch the dataframe of courses courses <- get_courses(canvas) head(courses) ``` # Fetching Specific Details The `vvcanvas` package provides various functions to fetch specific details. For example, to retrieve the assignments within a course, you can use the get_assignments function: ```{r assignments} # Replace the placeholder with the desired course ID course_id <- 12345 # Fetch the assignments for the course assignments <- get_assignments(canvas, course_id) head(assignments) ```
/scratch/gouwar.j/cran-all/cranData/vvcanvas/vignettes/getting_started.Rmd
--- title: "Working with groups" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Working with groups} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", eval = FALSE ) ``` # Introduction This vignette demonstrates how to retrieve group memberships in a course using the Canvas LMS API. # Step 1: List courses ```{r setup} library(vvcanvas) # Specify the Canvas API authentication details canvas <- list( api_key = "YOUR_API_KEY", base_url = "https://your_canvas_instance/" ) # Retrieve all courses courses <- get_courses(canvas) # Select a course (replace the index with the desired course) course_id <- course$id[1] ## the first course in courses ``` # Step 2: Retrieve all groups in the course ```{r get_groups} # Retrieve all groups in the selected course groups <- get_course_groups(canvas, course_id) # Extract the group IDs group_ids <- groups$id ``` # Step 3: Retrieve group memberships ```{r get_members} # Retrieve group memberships using purrr memberships <- purrr::map_df(group_ids, ~{ group_id <- .x # Retrieve the group's memberships group_memberships <- get_group_users(canvas, group_id) # Extract user names from memberships user_names <- group_memberships$name # Create a data frame with group memberships group_df <- data.frame(group_id = rep(group_id, length(user_names)), user_name = user_names, stringsAsFactors = FALSE) return(group_df) }) ```
/scratch/gouwar.j/cran-all/cranData/vvcanvas/vignettes/groups_use_case.Rmd
#' Academic year #' #' In this function, a date is translated to the academic year in which it #' falls. This is based on a start of the academic year on the #' 1st of September. #' #' @param x A date, or vector with multiple dates. POSIXct is also accepted. #' @param start_1_oct Does the academic year start on the 1st of October? default FALSE: #' based on September 1st #' @return The academic year in which the specified date falls #' @examples #' academic_year(lubridate::today()) #' #' @family vector calculations #' @export academic_year <- function(x, start_1_oct = FALSE) { ## Convert POSIXct and POSIXt to date class if (any(class(x) %in% c("POSIXct", "POSIXt"))) { x <- lubridate::as_date(x) } ## if the class is not a date, then this function cannot be executed stopifnot(class(x) == "Date") ## determine the calendar year of x calendar_year <- lubridate::year(x) ## determine for the calendar year in which year the academic year starts and ends ## The NA values that cannot be converted to dates should remain NA. Hence ## the 'suppressWarnings() if (start_1_oct) { acad_year_start <- suppressWarnings(lubridate::dmy(paste("01-10", calendar_year, sep = "-"))) acad_year_end <- suppressWarnings(lubridate::dmy(paste("01-10", calendar_year + 1, sep = "-"))) } else { acad_year_start <- suppressWarnings(lubridate::dmy(paste("01-09", calendar_year, sep = "-"))) acad_year_end <- suppressWarnings(lubridate::dmy(paste("01-09", calendar_year + 1, sep = "-"))) } ## If the specified date falls on or after the start of the academic year, ## returned the calendar year ## If the specified date falls before the start of the academic year, ## it to the previous calendar year: so calendar_year - 1 x <- dplyr::case_when( x >= acad_year_start ~ calendar_year, x < acad_year_end ~ calendar_year - 1 ) return(x) }
/scratch/gouwar.j/cran-all/cranData/vvconverter/R/Academic_year.R
#' Interval round #' #' Function to round numeric values in a vector to values from #' an interval sequence. #' #' @param x The numeric vector to adjust #' @param interval The interval sequence #' @examples #' interval_round(c(5, 4, 2, 6), interval = seq(1:4)) #' #' @family vector calculations #' @return The vector corrected for the given interval #' @export interval_round <- function(x, interval) { x <- interval[ifelse(x < min(interval), 1, findInterval(x, interval))] return(x) }
/scratch/gouwar.j/cran-all/cranData/vvconverter/R/Interval_round.R
#' Mode (most common value) #' #' Determine the most common value in a vector. If two values have the same frequency, #' the first occurring value is used. #' #' @param x a vector #' @param na.rm If TRUE: Remove nas before the calculation is done #' @examples #' mode(c(0, 3, 5, 7, 5, 3, 2)) #' #' @return the most common value in the vector x #' @export mode <- function(x, na.rm = FALSE) { if (na.rm) { x <- x[!is.na(x)] } ux <- unique(x) ux[which.max(tabulate(match(x, ux)))] }
/scratch/gouwar.j/cran-all/cranData/vvconverter/R/Mode.R
#' Sum 0 1 #' #' This function is the same as sum(), with one exception: If the outcome value is higher #' than 1, it will always return 1. #' @param x a vector with numeric values #' @return 0 or 1. Depending on whether the sum is greater than 0 or not. #' @family vector calculations #' @export sum_0_1 <- function(x) { ## Add all X's together y <- sum(x, na.rm = T) ## if y is NA, it means there were no values in the data. In that case ## the value becomes 0 if (is.na(y)) { y <- 0 ## If y is greater than 0, it means that on one of the fields at least once ## a 1 has been entered. Then the value becomes 1. } else if (y > 0) { y <- 1 } ## return the 0 or 1 return(y) }
/scratch/gouwar.j/cran-all/cranData/vvconverter/R/Sum_0_1.R
#' Transform 01 to FT #' #' If the vector is a 0/1 vector, it is converted to a logical one #' TRUE/FALSE vector. This transformation is performed only if #' the vector contains only values 0, 1, or NA. If this is not the case #' returns the original variable. #' This transformation can be done on numeric, string, and factor vectors. #' #' @param x the vector to be tested and transformed. #' @return The transformed vector if a transformation is possible. #' If no transformation is possible, the original vector #' returned. #' @family vector calculations #' @family booleans #' @examples #' vector <- c(0, 1, 0, 1, 1, 1, 0) #' transform_01_to_ft(vector) #' @export transform_01_to_ft <- function(x) { ## Check if this vector is a 0/1 variable converted to T/F ## can become if (test_01(x)) { if (is.numeric(x)) { ## Transform to a logical vector and return it ## If the vector is numeric, 1 is encoded as TRUE return(x == 1) } else if (is.character(x) | is.factor(x)) { ## Transform to a logical vector and return it ## If the vector is string or factor, "1" is coded as TRUE return(x == "1") } } else { ## If the variable is not a 0/1 variable, the original vector ## returned: x return(x) } } #' Test 01 #' #' This function tests whether the vector is actually a boolean, but is encoded #' as a 0/1 variable. The function checks for numeric vectors #' whether the only occurring values are 0, 1, or NA. At character and factor #' vectors checks whether the only occurring values are "0", "1", or NA #' to be. #' If there is a 0/1 variable, TRUE is returned, in all others #' cases FALSE. #' @param x The vector to test #' @return A TRUE/FALSE value on the test #' @family tests #' @family booleans #' @examples #' vector <- c(0, 1, 0, 1, 1, 1, 0) #' test_01(vector) #' @export test_01 <- function(x) { ## First determine the class of x. Depending on that, another test ## executed. if (is.numeric(x)) { ## The values to test if the vector is numeric values <- c(0, 1, NA) } else if (is.character(x) | is.factor(x)) { ## The values to test if the vector is a string or factor values <- c("0", "1", NA) } else { ## If the vector is not a numeric, string, or factor, it returns FALSE return(FALSE) } ## Test for each occurring value whether it is in the values variable ## Check if everything is TRUE, and return the result return(all(x %in% values)) }
/scratch/gouwar.j/cran-all/cranData/vvconverter/R/Transform_01_to_FT.R
#' clean multiple underscores #' #' Replaces multiple underscores into a single underscore in a vector or string. #' @param x The vector or string to be cleaned. #' @return cleaned vector or string. #' @examples #' clean_multiple_underscores("hello___world") #' #' @family vector calculations #' @export clean_multiple_underscores <- function(x) { if (any(grepl("__", x))) { x <- gsub("__", "_", x) } if (any(grepl("__", x))) { ## apply recursion if there still are multiple underscores in sequence x <- clean_multiple_underscores(x) } return(x) }
/scratch/gouwar.j/cran-all/cranData/vvconverter/R/clean_multiple_underscores.R
#' Convert character vector to numeric, ignoring irrelevant characters. #' #' @param x A vector to be operated on #' @param keep Characters to keep in, in bracket regular expression form. #' Typically includes 0-9 as well as the decimal separator (. in the US and , in #' Europe). #' @examples #' destring("24k") #' destring("5,5") #' #' @return vector of type numeric #' @family vector berekeningen #' @export destring destring <- function(x, keep = "0-9.-") { return(as.numeric(gsub(paste("[^", keep, "]+", sep = ""), "", x))) }
/scratch/gouwar.j/cran-all/cranData/vvconverter/R/destring.R
#' @title Group Summary #' @description Calculate the means (or other function) per group to analyze how each segment behaves. It scales each variable mean into the 0 to 1 range to easily profile the groups according to its mean. It also calculates the mean regardless of the grouping. This function is also useful when you want to profile cluster results in terms of its means. It automatically adds a row representing the summary of the column regardless of the group_var categories, which is useful to compare each segment with the whole population. It will exclude all factor/character variables. #' @param data Input data source. #' @param group_var Variable to make the group by. #' @param group_func Function to be used in the group by. Default is mean. #' @return Grouped data frame. #' @importFrom dplyr group_by summarise mutate across all_of #' @export group_summary <- function(data, group_var, group_func = mean) { # Calculate only for numeric variables numeric_vars <- names(data)[sapply(data, is.numeric) & names(data) != group_var] # Group by and calculate group_func grp_mean <- data %>% dplyr::group_by(dplyr::across(all_of(group_var))) %>% dplyr::summarise(dplyr::across(all_of(numeric_vars), ~ group_func(.x), .names = "{.col}")) %>% dplyr::mutate(dplyr::across(all_of(numeric_vars), ~ round(.x, 2))) # Calculate group_func for each numeric variable in the data frame, regardless of the group_var all_data_mean <- data %>% dplyr::summarise(dplyr::across(all_of(numeric_vars), ~ group_func(.x), .names = "{.col}")) %>% dplyr::mutate(dplyr::across(all_of(numeric_vars), ~ round(.x, 2))) # Add 'All_Data' row to all_data_mean all_data_mean[[group_var]] <- "All_Data" # Combine the results all_results <- rbind(grp_mean, all_data_mean) return(all_results) }
/scratch/gouwar.j/cran-all/cranData/vvconverter/R/group_summary.R
#' @title Group Summary Rank #' @description Similar to 'group_summary' function, this one computes the rank of each value in order to quickly know what is the value in each segment that has the highest value (rank=1). 1 represents the highest number. It will exclude all factor/character variables. #' @param data Input data source. #' @param group_var Variable to make the group by. #' @param group_func Function to be used in the group by. Default is mean. #' @return Grouped data frame, showing the rank instead of the absolute values. #' @importFrom dplyr group_by summarise mutate across dense_rank desc #' @export group_summary_rank <- function(data, group_var, group_func = mean) { # Calculate only for numeric variables numeric_vars <- names(data)[sapply(data, is.numeric) & names(data) != group_var] # Group by and calculate group_func grp_mean <- data %>% dplyr::group_by(dplyr::across(all_of(group_var))) %>% dplyr::summarise(dplyr::across(all_of(numeric_vars), ~ group_func(.x), .names = "{.col}")) %>% dplyr::mutate(dplyr::across(all_of(numeric_vars), ~ round(.x, 2))) # Calculate group_func for each numeric variable in the data frame, regardless of the group_var all_data_mean <- data %>% dplyr::summarise(dplyr::across(all_of(numeric_vars), ~ group_func(.x), .names = "{.col}")) %>% dplyr::mutate(dplyr::across(all_of(numeric_vars), ~ round(.x, 2))) # Add 'All_Data' row to all_data_mean all_data_mean[[group_var]] <- "All_Data" # Combine the results all_results <- rbind(grp_mean, all_data_mean) # Calculate rank for each numeric variable in the data frame all_results_rank <- all_results %>% dplyr::mutate(dplyr::across(dplyr::all_of(numeric_vars), ~ dplyr::dense_rank(dplyr::desc(.x)), .names = "{.col}_rank")) return(all_results_rank) }
/scratch/gouwar.j/cran-all/cranData/vvconverter/R/group_summary_rank.R
#' Median top 10 percentage #' #' Calculate the median of the top ten percentage of the values. #' #' @param x A numerical vector #' @param na.rm Default TRUE: Remove NAs, before calculations. #' @examples #' median_top_10(mtcars$cyl) #' #' @return A numerical value #' @export median_top_10 <- function(x, na.rm = FALSE) { ## Select only the top ten percentage students. Top_10 <- x[x >= stats::quantile(x, 0.9, na.rm = na.rm)] ## Calculate the median of this group. y <- stats::median(Top_10, na.rm = na.rm) ## Return the median return(y) }
/scratch/gouwar.j/cran-all/cranData/vvconverter/R/median_top_10.R
#' Month Name #' #' Transform month from numeric to equivalent in specified language. #' #' @param month_numeric Numeric in range 1 - 12. #' @param lang The language of the month names. Default is "nl" (Dutch). #' @return Character string representation of month in specified language. #' @export #' @family vector calculations month_name <- function(month_numeric, lang = "nl") { ## Check if the value is numeric checkmate::expect_numeric(month_numeric, lower = 1, upper = 12) ## Create a vector with the months months <- c( "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ) ## Translate the month names to the specified language months <- polyglotr::google_translate(months, target_language = lang) ## Return the correct month months[month_numeric] }
/scratch/gouwar.j/cran-all/cranData/vvconverter/R/month_name.R
#' Replace all occurences of a pattern in a file #' #' @param file character, path of file to be modified #' @param pattern character, pattern to be replaced #' @param replacement character, replacement text #' @param only_comments logical, should the replacement only be done in comments #' @param collapse logical, should the lines be collapsed into a single line before replacement #' @return NULL, the file is modified in place #' @export #' str_replace_all_in_file <- function(file, pattern, replacement = "[...]", only_comments = TRUE, collapse = FALSE) { Lines <- readLines(file) if (!collapse) { if (only_comments) { Search_line <- stringr::str_detect(Lines, "^\\s*#") } else { Search_line <- T } Lines[Search_line] <- stringr::str_replace_all(Lines[Search_line], pattern = pattern, replacement = replacement) cat(Lines, file = file, sep = "\n") } else { Lines_collapsed <- paste(c(Lines, ""), collapse = "\n") Lines_collapsed <- stringr::str_replace_all(Lines_collapsed, pattern = pattern, replacement = replacement) cat(Lines_collapsed, file = file) } }
/scratch/gouwar.j/cran-all/cranData/vvconverter/R/str_replace_all_in_file.R
#' Translate Yes/No Responses #' #' This function translates yes/no responses from a given language to English. #' #' @param responses A vector of responses. #' @param source_language The language of the responses. Default is "nl" (Dutch). #' @return A vector of translated responses. #' @export translate_yes_no <- function(responses, source_language = "nl") { if (is.character(responses) | is.factor(responses)) { return(polyglotr::google_translate(responses, source_language = source_language, target_language = "en")) } else { return(FALSE) } } #' Test Yes/No Responses #' #' This function tests if a vector of responses are yes or no. #' #' @param responses A vector of responses. #' @return A logical vector indicating if each response is yes or no. #' @export test_yes_no <- function(responses) { values <- c("yes", "Yes", "No", "no", "y", "n", NA) return(all(tolower(trimws(responses)) %in% values)) }
/scratch/gouwar.j/cran-all/cranData/vvconverter/R/test_yes_no.R
#' Transform Logical to Yes/No and Vice Versa #' #' This function transforms a logical vector to a vector of yes/no strings or vice versa. #' #' @param x A logical or character vector. #' @param lang The language of the yes/no strings. Default is "nl" (Dutch). #' @return A vector of yes/no strings or a logical vector. #' @export transform_logical_yes_no <- function(x, lang = "nl") { if (is.logical(x)) { y <- as.character(x) y[x] <- "Yes" y[!x] <- "No" y <- polyglotr::google_translate(y, target_language = lang) } else if (is.character(x) | is.factor(x)) { y <- tolower(trimws(x)) y <- polyglotr::google_translate(y, source_language = lang, target_language = "en") y <- y == "yes" | y == "y" | y == "Yes" } else { stop("Invalid input. Please provide a logical or character/factor vector.") } return(y) }
/scratch/gouwar.j/cran-all/cranData/vvconverter/R/transform_logical_yes_no.R
#' Trim #' #' Trim both leading and trailing whitespaces from string. #' #' @param x A text string. #' @return Cleaned string. #' @examples #' trim(" hello ") #' #' @export trim <- function(x) gsub("^\\s+|\\s+$", "", x) #' LTrim #' #' Trim leading whitespace from sting. #' @param x A text string. #' @return Cleaned string. #' @examples #' trim(" hello") #' @export ltrim <- function(x) gsub("^\\s+", "", x) #' RTrim #' #' Trim trailing whitespaces from string. #' @param x A text string. #' @return Cleaned string. #' @examples #' trim("hello ") #' @export rtrim <- function(x) gsub("\\s+$", "", x)
/scratch/gouwar.j/cran-all/cranData/vvconverter/R/trim.R
#' Pipe operator #' #' See \code{magrittr::\link[magrittr:pipe]{\%>\%}} for details. #' #' @name %>% #' @rdname pipe #' @keywords internal #' @export #' @importFrom magrittr %>% #' @usage lhs \%>\% rhs #' @param lhs A value or the magrittr placeholder. #' @param rhs A function call using the magrittr semantics. #' @return The result of calling `rhs(lhs)`. NULL
/scratch/gouwar.j/cran-all/cranData/vvconverter/R/utils-pipe.R
#' NA impute median #' #' Is a specialized function which takes a variable and turns it into two new variables #' to be used in a prediction model. #' 1) the variable for which missing values are imputed by the median for the given year. #' 2) an indicator when the variable is missing #' #' @param data The data frame. #' #' @param var The variable used to create new variables. #' @param year Year used for the median for imputation. #' @param year_column Column with year to use median on. #' #' @return New data frame in which missing values are filled. #' @export na_impute_median <- function(data, var, year = 2014, year_column){ ## Add an indicator for when data[,paste("NA_ind_", var, sep="")] <- is.na(data[,var]) ## Calculate the median of the original field: median <- stats::median(subset(data, !!year_column %in% year)[,var], na.rm=T) ## Add a new filled field: new_var <- paste(var, "imputed", sep="_") data[,new_var] <- data[,var] data[,new_var][is.na(data[,new_var])] <- median return(data) }
/scratch/gouwar.j/cran-all/cranData/vvfiller/R/NA_impute_median.R
#' Check if some missing values are present #' #' Check if some missing values are present, but not all are missing. #' returns a boolean. This check is done to save time for vectors where filling #' is not needed #' #' @param x the vector to check #' @return TRUE or FALSE check_some_missing <- function(x) { x <- unique(x) return(any(is.na(x)) & !all(is.na(x))) } check_min_known_p <- function(x, x_na_omit, min_known_p) { known_p <- length(x_na_omit) / length(x) ## When the percentage of known values is smaller than the given minimum, ## FALSE will be returned if (known_p < min_known_p) { return(FALSE) } else { return(TRUE) } } check_min_known_n <- function(x, x_na_omit, min_known_n) { known_n <- length(x_na_omit) ## When the number of known values is smaller than the given minimum, ## FALSE will be returned if (known_n < min_known_n) { return(FALSE) } else { return(TRUE) } } check_min_known <- function(x, x_na_omit, min_known_n, min_known_p){ ## Check if the minimum known n and percentage criteria are matched if (!is.null(min_known_n)) { if(!check_min_known_n(x, x_na_omit, min_known_n)){ return(FALSE) } } if (!is.null(min_known_p)) { if(!check_min_known_p(x, x_na_omit, min_known_p)) { return(FALSE) } } return(TRUE) }
/scratch/gouwar.j/cran-all/cranData/vvfiller/R/check.R