content
stringlengths
0
14.9M
filename
stringlengths
44
136
#' fill missing value #' #' Returns a vector with all missing values filled with another value #' @param x vectors. All inputs should have the same length #' @param value a value with the same class as x #' @return vector with the same length as the first vector #' @export #' #' @examples #' fill_value(c(NA,1), 2) fill_value <- function(x, value) { stopifnot(length(value) == 1) stopifnot(class(x) == class(value)) i <- which(is.na(x)) x[i] <- value return(x) }
/scratch/gouwar.j/cran-all/cranData/vvfiller/R/fill.R
#' Fill missing strict #' #' Fill all missing values in a vector with the same value if it is known. Only #' fills the value when all known values are the same #' @param x The vector to fill #' @param min_known_n numeric value: the minimum number of not-missing values #' @param min_known_p numeric value between 0 and 1: the minimum fraction of not-missing values #' #' @return a filled vector #' @export #' #' @examples #' fill_missing_strict(c(NA, 1)) fill_missing_strict <- function(x, min_known_n = NULL, min_known_p = NULL) { fill_missing(x, min_known_n, min_known_p, type = "strict") } #' Fill missing previous #' #' Fill all missing values in a vector with the previous value if it is known. #' @param x The vector to fill #' @param min_known_n numeric value: the minimum number of not-missing values #' @param min_known_p numeric value between 0 and 1: the minimum fraction of not-missing values #' #' @return a filled vector #' @export #' #' @examples #' fill_missing_previous(c(1, 2, NA)) #' fill_missing_previous(c(NA, 1, 2, NA)) fill_missing_previous <- function(x, min_known_n = NULL, min_known_p = NULL) { fill_missing(x, min_known_n, min_known_p, type = "previous") } #' Fill missing minimum #' #' Fill all missing values in a vector with the minimum value if it is known. #' @param x The vector to fill #' @param min_known_n numeric value: the minimum number of not-missing values #' @param min_known_p numeric value between 0 and 1: the minimum fraction of not-missing values #' #' @return a filled vector #' @export #' #' @examples #' fill_missing_min(c(1, 2, NA)) #' fill_missing_min(c(NA, 1, 2, NA)) fill_missing_min <- function(x, min_known_n = NULL, min_known_p = NULL) { fill_missing(x, min_known_n, min_known_p, type = "min") } #' Fill missing maximum #' #' Fill all missing values in a vector with the maximum value if it is known. #' @param x The vector to fill #' @param min_known_n numeric value: the minimum number of not-missing values #' @param min_known_p numeric value between 0 and 1: the minimum fraction of not-missing values #' #' @return a filled vector #' @export #' #' @examples #' fill_missing_max(c(1, 2, NA)) #' fill_missing_max(c(NA, 1, 2, NA)) fill_missing_max <- function(x, min_known_n = NULL, min_known_p = NULL) { fill_missing(x, min_known_n, min_known_p, type = "max") } #' Fill missing last #' #' Fill all missing values in a vector with the last value if it is known. #' @param x The vector to fill #' @param min_known_n numeric value: the minimum number of not-missing values #' @param min_known_p numeric value between 0 and 1: the minimum fraction of not-missing values #' #' @return a filled vector #' @export #' #' @examples #' fill_missing_last(c(1, 2, NA)) #' fill_missing_last(c(NA, 1, 2, NA)) fill_missing_last <- function(x, min_known_n = NULL, min_known_p = NULL) { fill_missing(x, min_known_n, min_known_p, type = "last") } #' Fill missing interval #' #' Fill all missing values for an interval observed in the vector #' @param x The vector to fill #' @param min_known_n numeric value: the minimum number of not-missing values #' @param min_known_p numeric value between 0 and 1: the minimum fraction of not-missing values #' #' @return a filled vector #' @export #' #' @examples #' fill_missing_interval(c(NA, 1, 2, NA)) #' fill_missing_interval(c(NA, 10, 20, NA)) fill_missing_interval <- function(x, min_known_n = NULL, min_known_p = NULL) { return(fill_missing(x, min_known_n, min_known_p, type = "interval")) } #' Fill missing #' #' wrapper function to do check and call all fill_vector functions #' @param x The vector to fill #' @param min_known_n numeric value: the minimum number of not-missing values #' @param min_known_p numeric value between 0 and 1: the minimum fraction of not-missing values #' @param type the type of fill missing function to be called #' @return filled vector #' @export fill_missing <- function(x, min_known_n = NULL, min_known_p = NULL, type) { stopifnot(type %in% c("last", "min", "max", "strict", "previous", "interval")) ## Check if missing values can and should be filled if(!check_some_missing(x)) { return(x) } ## Create vector without mising values x_na_omit <- stats::na.omit(x) ## Check if the minimum known n and percentage criteria are matched if(!check_min_known(x, x_na_omit, min_known_n, min_known_p)) { return(x) } ## Call the fill_vector function, depending on the given type argument if (type == "last"){ return(fill_vector_last(x, x_na_omit)) } else if (type == "min") { stopifnot(is.numeric(x)) return(fill_vector_min(x, x_na_omit)) } else if (type == "max") { stopifnot(is.numeric(x)) return(fill_vector_max(x, x_na_omit)) } else if (type == "strict") { return(fill_vector_strict(x, x_na_omit)) } else if (type == "previous") { return(fill_vector_previous(x)) } else if (type == "interval") { return(fill_vector_interval(x)) } }
/scratch/gouwar.j/cran-all/cranData/vvfiller/R/fill_missing.R
#' Fill missing rownumber #' #' Impute missing values of a count variable. Imputation is done by counting from #' the last known value. Example: c(NA,4,NA,NA) then becomes c(NA,4,NA,NA). #' @param x Integer vector. #' @return Integer vector with filled values. #' @family vector calculations #' @family missing data functions #' @export #' @examples fill_missing_rownumber(c(NA,4,NA,NA)) fill_missing_rownumber <- function(x){ ## Check if vector has missing values if (length(stats::na.omit(x)) == 0) { return(x) } ## Check if vector is of class numeric if (!is.numeric(x)) { return(x) } ## Determine index of max value position_max <- match(max(x, na.rm = T), x) length_x <- length(x) ## If the last known value is not the max the if statement is triggered. if (position_max < length_x) { ## Determine the positions of the missing values that can be imputed. position_missing <- (position_max + 1):length_x ## Impute by counting up. x[position_missing] <- x[position_max] + position_missing - position_max } return(x) }
/scratch/gouwar.j/cran-all/cranData/vvfiller/R/fill_missing_rownumber.R
#' fill_vector_strict #' #' @param x the vector to be filled #' @param x_na_omit the x vector without NA values fill_vector_strict <- function(x, x_na_omit) { ## Only fill missing if all non-missing values are the same if (length(unique(x_na_omit)) == 1) { ## use fill_value with the only non- missing value return(fill_value(x, x_na_omit[1])) } return(x) } #' fill_vector_last #' #' @param x the vector to be filled #' @param x_na_omit the x vector without NA values fill_vector_last <- function(x, x_na_omit) { ## use fill_value with the last known value return(fill_value(x, x_na_omit[length(x_na_omit)])) } #' fill_vector_min #' #' @param x the vector to be filled #' @param x_na_omit the x vector without NA values fill_vector_min <- function(x, x_na_omit) { ## use fill_value with the minimum value return(fill_value(x, min(unique(x_na_omit)))) } #' fill_vector_max #' #' @param x the vector to be filled #' @param x_na_omit the x vector without NA values fill_vector_max <- function(x, x_na_omit) { ## use fill_value with the maximum value return(fill_value(x, max(unique(x_na_omit)))) } #' fill_vector_previous #' #' @param x the vector to be filled fill_vector_previous <- function(x) { ## Determine the posisition of NA values position_not_na <- which(!is.na(x)) ## When the vector starts with NA we add the first position, because we ## are not able to fill this value if (is.na(x[1])) position_not_na <- c(1, position_not_na) ## determine how often a value has to be repeated within the vector rep_times <- diff(c(position_not_na, length(x) + 1)) ## repeat the value at the determined positions return(rep(x[position_not_na], times = rep_times)) } #' fill_vector_interval #' #' @param x the vector to be filled fill_vector_interval <- function(x) { ## Determine the posisition of NA values position_not_na <- which(!is.na(x)) ## Create a shifted vector, to calculate the difference with the previous ## value vector_lead <- c(NA, x[1:(length(x) - 1)]) ## Calculate the interval for each item vector_intervals <- x - vector_lead ## Determine all unique interval values vector_interval <- unique(stats::na.omit(vector_intervals)) ## If the interval is not the same for each item, return the the x: don't ## fill this vector if (length(vector_interval) != 1) { return(x) } ## Determine the first posisition of not-NA values first_position_not_na <- which(!is.na(x))[1] first_value <- x[first_position_not_na] ## The number of NA-values the vector starts with number_na_start <- first_position_not_na - 1 ## The value of the first item in the vector is calculated with ## the first known value and the number of NA values before that value value_pos_1 <- first_value - number_na_start * vector_interval ## Create the sequence x_new <- seq(value_pos_1, length.out = length(x), by = vector_interval) ## Test whether the sequence of all non-missing values in x is identical ## tot the new vector if (!identical(x[which(!is.na(x))], x_new[which(!is.na(x))])) { return(x) } return(x_new) }
/scratch/gouwar.j/cran-all/cranData/vvfiller/R/fill_vector.R
#' Fill with aggregate by group #' #' Function to calculate a summary statistic (mean, median, vvconverter::mode, min, max etc.) by group #' and use it to fill missing values. Note: this takes and produces a tibble rather than a vector. #' @param df tibble to use #' @param group string or vector of strings: columns to group by #' @param columns string or vector of strings: columns to impute #' @param overwrite_col boolean: whether to overwrite column. If FALSE, a new column with suffix _imputed will be created #' @param statistic function: summary statistic to use (mean, median, min etc.). For now requires a function with na.rm argument #' @param fill_empty_group boolean: If TRUE, fills groups that only contain NA with summary statistic of entire column #' @return a tibble with filled column(s) #' @importFrom dplyr %>% #' @importFrom rlang := #' @export fill_df_with_agg_by_group <- function(df, group, columns, overwrite_col = FALSE, statistic = mean, fill_empty_group = FALSE){ ## Fills missing values with summary statistics (mean, median, vvconverter::mode, etc.) per group new_cols <- columns %>% purrr::map_dfc(function(col){ col_output = ifelse(overwrite_col, col, paste0(col, "_imputed")) df[col_output] <- df %>% fill_col_with_agg_by_group(group = group, col = col, statistic = statistic) if (fill_empty_group){ df[col_output] <- df %>% fill_col_with_agg_by_group(group = c(), col = col_output, statistic = statistic) } return(df %>% dplyr::select(col_output)) }) ## Add updated columns to df if (!overwrite_col) { df <- cbind(df, new_cols) } else { df[columns] = new_cols } return(df) } #' Fill column with aggregate by group #' #' Calculate a summary statistic (mean, median, vvconverter::mode, min, max etc.) by group #' and use it to fill missing values in a column. Primarily for use in fill_with_agg_by_group(). #' #' @param df tibble to use #' @param group string or vector of strings: columns to group by #' @param col string: column to impute #' @param statistic function: summary statistic to use (mean, median, min etc.). For now requires a function with na.rm argument #' @return a filled vector #' @importFrom dplyr %>% #' @importFrom rlang := #' @export fill_col_with_agg_by_group <- function(df, group, col, statistic){ new <- NULL ## Fills missing values with summary statistics (mean, median, vvconverter::mode, etc.) per group result_column <- df %>% dplyr::group_by(!!!dplyr::syms(group)) %>% dplyr::mutate(new = ifelse(is.na(!!dplyr::sym(col)), statistic(!!dplyr::sym(col), na.rm = T), !!dplyr::sym(col))) %>% dplyr::ungroup() %>% dplyr::pull(new) return(result_column) }
/scratch/gouwar.j/cran-all/cranData/vvfiller/R/fill_with_agg.R
#' Add current date and time to data frame. #' #' This function adds a new column to a data frame with the current date and time. #' The name of the new column is a combination of the provided prefix, stage, and "Date_time". #' If the new column already exists, it will be overwritten. #' #' @param data Data frame. #' @return Data frame with an additional column containing the current date and time. #' #' @examples #' \dontrun{ #' # Create a sample data frame #' data <- data.frame(a = 1:5, b = letters[1:5]) #' #' # Add date to file name #' add_current_datetime_column(data) #' } #' @export add_current_datetime_column <- function(data) { new_var <- "Date_time" # Check if new column already exists if (new_var %in% colnames(data)) { warning("Column ", new_var, " already exists. It will be overwritten.") } data[, new_var] <- Sys.time() return(data) }
/scratch/gouwar.j/cran-all/cranData/vvmover/R/add_current_datetime_column.R
#' Calculate NA Percentage #' #' This function calculates the percentage of NA values in a given vector. It also includes a margin of 10%. #' #' @param x A numeric vector. #' @param ... Additional arguments (not used). #' @return A numeric value representing the percentage of NA values in the vector. #' @export calculate_na_percentage <- function(x, ...) { # Calculate the percentage of NA values na_percentage <- sum(is.na(x)) / length(x) # Add a margin of 10% na_percentage <- na_percentage + na_percentage * 0.10 # Add a correction based on the size of the data correction <- (1 - 1/log(length(x))) * 0.10 na_percentage <- na_percentage + correction # Return the result in percentage return(na_percentage * 100) }
/scratch/gouwar.j/cran-all/cranData/vvmover/R/calculate_na_percentage.R
#' check_installed_package #' #' Check if a package is installed. If not, #' throw an error message #' #' @param package_name the name of the package (quoted) #' @param check the function should work as a boolean operator #' @return Boolean value whether package is installed. #' @examples #' check_installed_package("dplyr") #' #' @export check_installed_package <- function(package_name, check = FALSE) { if (check) { if (!requireNamespace(package_name, quietly = TRUE)) { return(FALSE) } else { return(TRUE) } } else { if (!requireNamespace(package_name, quietly = TRUE)) { stop( paste( "Package", package_name, "required to use this function", "install this:", paste0("\ninstall.packages(\"", package_name, "\")") ), call. = FALSE ) } } }
/scratch/gouwar.j/cran-all/cranData/vvmover/R/check_installed_package.R
############################################### ############################# ## get_recent_file() ############################################### ############################# ## get_recent_file() is a wrapper around get_recent_file_date_filename_ymd and ## get_recent_file_date_modified and retrieves the most recent version of a ## file based on naming or date modified. #' Get recent file #' #' Is a wrapper around get_recent_file_date_filename_ymd en #' get_recent_file_date_modified and retrieves the most recent version of a #' file based on naming or date modified. #' @param path The path to search for the file #' @param match The search term matched in the file name #' @param date_type The way to find the recent file #' date_type = "modified" is based on customization, date_type = "filename_ymd" #' is based on file name. #' @return The most recent file. #' @family Get recent files #' @export get_recent_file <- function(path, match, date_type = "modified") { ## Wrapper around functions get recent file based on ## naming (filename_ymd) or date(date_modified) if (date_type == "filename_ymd") { return(get_recent_file_date_filename_ymd(path = path, match = match)) } if (date_type == "modified") { return(get_recent_file_date_modified(path = path, match = match)) } }
/scratch/gouwar.j/cran-all/cranData/vvmover/R/get_recent_file.R
#' Get recent file date filename ymd #' #' This function determines the path of the most recent version of a file in #' a folder. Sorting is determined by file name #' where it is a condition that the filename starts with ymd encoding. #' @param path The path to search for the file. #' @param match The search term to match in the file name. #' @return The most recent file #' @family Get recent files #' @export get_recent_file_date_filename_ymd <- function(path, match) { ## List the files based on match and ## Sort descending by name with date format (most recent files ## first. Condition is file names starting with ymd quote ## Then find the first element that contains the match ## and return that filename files <- list.files(path, match, full.names = TRUE) return_var <- basename(files) no <- order(dplyr::desc(return_var))[[1]] thisfile <- files[[no]] if (grepl("^20[0-9]{2}", basename(thisfile))) { ## Print found file name message(paste("Most recent file is", basename(thisfile))) return(thisfile) } else { warning("File names do not follow ymd encoding, function get_recent_file_date_modified has been used") return(get_recent_file_date_modified(path = path, match = match)) } }
/scratch/gouwar.j/cran-all/cranData/vvmover/R/get_recent_file_date_filename_ymd.R
############################################### ############################# ## get_recent_file_date_modified() ############################################### ############################# ## get_recent_file_date_modified() gets the most recent version of a ## file on #' Get recent file date modified #' This function determines the path of the most recent version of a file in #' a folder. The sorting is determined based on the date of the last #' change. #' @param path The path to search for the file. #' @param match The search term to match in the file name. #' @param echo Print the date the file was last modified #' in the console. #' @family Get recent files #' @return The most recent file. #' @export get_recent_file_date_modified <- function(path, match, echo = TRUE) { ## List the files and get the file information ## Sort descending: most recent files first ## Then find the first element that contains the match ## and return that filename files <- list.files(path, full.names = TRUE) file_details <- file.info(list.files(path, full.names = TRUE)) file_details <- file_details[with(file_details, order(as.POSIXct(mtime), decreasing = TRUE)), ] files <- rownames(file_details) for (file in files) { if ( grepl(match, file, fixed = TRUE) ) { this_file <- file break } else { this_file <- NA } } return_var <- this_file ## Correct for double slashes return_var <- gsub("//", "/", return_var) ## Print when the file was last modified if (echo) { ## Get the last modified date from the file_details table ## and format this to yyyy-mm-dd Date <- format(file_details[this_file, "mtime"], "%Y-%m-%d") ## print this message(paste(match, "last modified", Date)) } return(return_var) }
/scratch/gouwar.j/cran-all/cranData/vvmover/R/get_recent_file_date_modified.R
#' Check if Field is Subset #' #' This function checks if a field is a subset. #' We define a subset as a character field that contains fewer than 20 unique values. #' #' @param field_name Name of the field to check. #' @param df Dataframe to check. #' @param column_names Set that the field is part of. #' @param column_types Types that belong to the column names. #' @family tests #' @family assertions is_field_subset <- function(field_name, df, column_names, column_types) { ## Find the index position of the field name index <- which(column_names == field_name) ## Check if Column is character if (column_types[index] == "character") { ## Check if this contains fewer than 20 unique values if (length(unique(df[[field_name]])) < 20) { ## Return type is subset return("subset") } else { ## Otherwise, the type remains the same return(column_types[[index]]) } } else { ## Otherwise, the type remains the same return(column_types[[index]]) } }
/scratch/gouwar.j/cran-all/cranData/vvmover/R/is_field_subset.R
#' move files pattern #' #' Move files in a directory based on regular expression #' @param Folder_origin Source folder. #' @param Folder_dest Destination folder. #' @param pattern Pattern to match files in source folder on. #' @param recursive Default: FALSE. Whether to use recursive search in directory. #' @return message #' @export move_files_pattern <- function(Folder_origin, Folder_dest, pattern, recursive = FALSE) { Filepaths_origin <- list.files( path = Folder_origin, pattern = pattern, full.names = TRUE, recursive = recursive ) if (length(Filepaths_origin) == 0) { return(paste("There are no files matching the pattern::", pattern)) } Filepaths_dest <- paste0(Folder_dest, basename(Filepaths_origin)) Moved <- file.rename( Filepaths_origin, Filepaths_dest ) message(paste("Number of files matching the pattern:", pattern, "are moved:", length(Filepaths_dest[Moved]))) }
/scratch/gouwar.j/cran-all/cranData/vvmover/R/move_files_pattern.R
#' Print date the file was last modified #' #' This function prints the date a file was last modified #' @param path The file path #' @examples #' print_last_modified(readr::readr_example("mtcars.csv")) #' #' @return message #' @export print_last_modified <- function(path) { ## Extract the last modified date from the file and format it to yyyy-mm-dd Date <- format(file.info(path)$mtime, "%Y-%m-%d") ## print this message(paste(basename(path), "last modified", Date)) } #' get_last_modified_date #' #' @param file_path Path to the file. #' #' @return Date that file was last modified #' @export get_last_modifed_date <- function(file_path) { Datetime <- format(file.info(file_path)$mtime, "%Y-%m-%d") return(Datetime) }
/scratch/gouwar.j/cran-all/cranData/vvmover/R/print_last_modified.R
#' Generate a random string vector #' #' @param n The number of items in the vector. Default is set to 500. #' @param length the number of characters in a string. Default is set to 6. #' @param characters A vector containing the characters to include. Default is all lowercase, all, uppercase letters and all numbers. random_string_vector <- function(n = 500, length = 6, characters = c(letters, LETTERS, 0:9)) { # Generate a random vector with strings of 20 characters return(do.call( paste0, replicate( length, ## Random letters and numbers are drawn sample( characters, n, TRUE ), FALSE ) )) }
/scratch/gouwar.j/cran-all/cranData/vvmover/R/random_string_vector.R
#' Read Excel Allsheets #' #' Read in all sheets in an Excel file. #' #' @param filename Name of Excel file #' @examples #' read_excel_allsheets(readxl::readxl_example("clippy.xls")) #' #' @return Dataframe #' #' @export read_excel_allsheets <- function(filename) { check_installed_package("readxl") sheets <- readxl::excel_sheets(filename) x <- lapply(sheets, function(X) readxl::read_excel(filename, sheet = X)) names(x) <- sheets return(x) }
/scratch/gouwar.j/cran-all/cranData/vvmover/R/read_excel_allsheet.R
#' Save session info to a file #' #' Stores session info in a .txt file. #' #' @param path The directory path where the session info file will be saved. #' #' @return A .txt file containing session info, saved at the specified path. #' @export save_session_info_to_file <- function(path) { writeLines(utils::capture.output(utils::sessionInfo()), paste(path, "sessionInfo.txt", sep = "")) }
/scratch/gouwar.j/cran-all/cranData/vvmover/R/save_session_info_to_file.R
#' Extract a .zip archive and read in with read_delim #' #' Extract a .zip archive and read it in with readr's read_delim function. The file is extracted to a temporary location, and then deleted after reading it. #' #' @param zip_path The file path of the .zip archive #' @param filename OPTIONAL: The file name of the file in the .zip archive to be read. This parameter can be left empty if there is only 1 file in the archive. #' @param ... arguments to the readr::read_delim function. see: \link[readr]{read_delim} #' @examples #' unzip_read_delim(readr::readr_example("mtcars.csv.zip")) #' #' @return Dataframe #' #' @export unzip_read_delim <- function(zip_path, filename = NULL, ...) { ## Create a temporary directory, and extract the file into it temporary_dir <- tempfile() utils::unzip(zip_path, exdir = temporary_dir) ## Check how many files are available files <- list.files(temporary_dir, full.names = TRUE) ## Determine the file to be read ## If the filename is specified, it will be read if (!is.null(filename)) { file <- paste(temporary_dir, filename, sep = "/") # If there is more than 1 file in the .zip, an error will be given } else if (length(files) > 1) { stop(paste0( "There is more than 1 file in the .zip file. specify a filename. The files are:\n", paste("- ", basename(files), collapse = "\n") )) ## If there is 1 file in the zip, it will be used } else { file <- files[1] } ## Finally, run read_delim, after running the file will be deleted. ## this is in a tryCatch, so that in case of an error while reading, the file ## will still be removed tryCatch( { ## Use read_delim df <- readr::read_delim(file = file, ...) return(df) }, ## If there is an error, the file will be deleted, and only then will the error be given finally = { unlink(temporary_dir, force = TRUE, recursive = TRUE ) } ) }
/scratch/gouwar.j/cran-all/cranData/vvmover/R/unzip_read_delim.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/vvmover/R/utils-pipe.R
#' Correct model levels #' #' Correct level names for modelling and in the use of ROC curve/AUC. #' #' @param data String with level names. #' #' @return Corrected level names. #' @examples #' data <- data.frame(id = c(1,2,3), #' name = c("Alice","Bob","Charlie"), #' gender = factor(c("Female","Male","Female"), levels = c("Female","Male"))) #' #' correct_model_levels(data) #' # returns a data frame with factor levels of the variable gender corrected to "Female" and "Male" #' #' data <- data.frame(id = c(1,2,3), #' name = c("Alice","Bob","Charlie"), #' gender = factor(c("Female","Male","Female"))) #' correct_model_levels(data) #' # returns a data frame with factor levels of the variable gender corrected to "F" and "M" #' @export correct_model_levels <- function(data) { feature.names <- names(data) for (f in feature.names) { if (inherits(data[[f]], "factor")) { levels <- unique(c(data[[f]])) data[[f]] <- factor(data[[f]], labels=make.names(levels)) } } return(data) }
/scratch/gouwar.j/cran-all/cranData/vvsculptor/R/correct_model_levels.R
#' strict_left_join #' #' A wrapper around dplyr's left_join, with an error message if #' duplicate values are present in the matching fields in y. #' This will prevent duplicating rows. See dplyr::left_join . #' #' @param x data frame x (left) #' @param y data frame y (right) #' @param by unquoted variable names to join. #' @param ... Pass further arguments to dplyr::left_join #' @return merged data frame #' @seealso \code{\link[dplyr:join]{left_join}} #' @examples #' left_df <- data.frame(id = c(1, 2, 3), name = c("Alice", "Bob", "Charlie")) #' right_df <- data.frame(id = c(1, 2, 4), age = c(20, 25, 30)) #' strict_left_join(left_df, right_df, by = "id") #' #' @export strict_left_join <- function(x, y, by = NULL, ...) { by <- dplyr::common_by(by, x, y) if (any(duplicated(y[by$y]))) { stop("Duplicate values in foreign key") } else return(dplyr::left_join(x, y, by = by, ...)) }
/scratch/gouwar.j/cran-all/cranData/vvsculptor/R/strict_left_join.R
#' Gantt Chart Shiny App #' #' @param df Data frame for Gantt chart #' @param df_config_gantt Config data frame for Gantt chart #' @param id Module ID for Gantt chart #' #' @return Shiny app object #' @export #' @examples #' df <- dplyr::tribble( ~OPL_Onderdeel_CROHO_examen, ~OPL_Onderdeel_CROHO_instroom, #' ~OPL_CBS_Label_rubriek_examen, ~OPL_CBS_Label_rubriek_instroom, "GEDRAG EN MAATSCHAPPIJ", #' "GEZONDHEIDSZORG", "sociale geografie", "(huis)arts, specialist, geneeskunde", #' "GEDRAG EN MAATSCHAPPIJ", "GEDRAG EN MAATSCHAPPIJ", "sociale geografie", "sociale geografie", #' "GEDRAG EN MAATSCHAPPIJ", "RECHT", "sociale geografie", "notariaat", "RECHT", "RECHT", #' "notariaat", "notariaat", "TAAL EN CULTUUR", "RECHT", "niet westerse talen en culturen", #' "notariaat") #' #' df_config_gantt <- dplyr::tribble( ~Categorie, ~Veldnaam, ~Veldnaam_gebruiker, ~input_var, #' ~target_var, ~title_start, ~title_end, ~position_y_label, "Doorstroom vanuit B ", #' "OPL_Onderdeel_CROHO_examen", "B Croho sector", "OPL_Onderdeel_CROHO_examen", #' "OPL_Onderdeel_CROHO_instroom", "Waar stromen", "Bachelor gediplomeerden naar toe?", "right", #' "Doorstroom vanuit B ", "OPL_CBS_Label_rubriek_examen", "B ISCED-F Rubriek", #' "OPL_CBS_Label_rubriek_examen", "OPL_CBS_Label_rubriek_instroom", "Waar stromen", #' "Bachelor gediplomeerden naar toe?", "right", "Instroom bij M", "OPL_Onderdeel_CROHO_instroom", #' "M Croho sector", "OPL_Onderdeel_CROHO_instroom", "OPL_Onderdeel_CROHO_examen", #' "Waarvandaan stromen ", " Master studenten in?", "left", "Instroom bij M", #' "OPL_CBS_Label_rubriek_instroom", "M ISCED-F Rubriek", "OPL_CBS_Label_rubriek_instroom", #' "OPL_CBS_Label_rubriek_examen", "Waarvandaan stromen ", " Master studenten in?", "left" ) gantt_app <- function(df, df_config_gantt, id = "gantt") { if(!exists("request")) { request <- NULL } #tabItems <- list( # shinydashboard::tabItem(tabName = id, module_gantt_ind_ui(id, df_config_gantt)) #) #test <- shinydashboard::tabItems(tabItems) ui <- single_module_ui(request, id, tab_item = shinydashboard::tabItem(tabName = id, module_gantt_ind_ui(id, df_config_gantt))) server <- function(input, output, session) { module_gantt_ind_server(id, df, df_config_gantt) } shiny::shinyApp(ui, server) } ## Server function for gantt chart module ## ## @param id Module id ## @param df Data frame ## @param df_config_gantt Config data frame for gantt chart ## ## @return Shiny module server function module_gantt_ind_server <- function(id, df, df_config_gantt) { shiny::moduleServer(id, function(input, output, session) { input_var <- position_y_label <- n <- flow_perc <- flow_perc <- flow_end_perc <- NULL flow_start_perc <- NULL ## Maak UI om te dplyr::filteren op geselecteerde variabele output$filter_values <- shiny::renderUI({ shiny::req(input$input_var) htmltools::tagList( pickerGanttValues(id, input$input_var, df) ) }) ## Maak UI om te dplyr::filteren op geselecteerde variabele output$target_var <- shiny::renderUI({ shiny::req(input$input_var) htmltools::tagList( pickerGanttVar(id, "target_var", df_config_gantt, input$input_var) ) }) output$gantt <- plotly::renderPlotly({ ## Haal vereiste variables op. De input_var update ook de filter_value, dus vandaar de ## req voor dplyr::filter en isolate voor input shiny::req(input$filter, input$target_var) input_var_value <- shiny::isolate(input$input_var) filter_value <- input$filter split_var <- input$target_var position_label_y <- df_config_gantt %>% dplyr::filter(input_var == input_var_value) %>% dplyr::pull(position_y_label) %>% dplyr::first() title_start = df_config_gantt %>% dplyr::filter(input_var == input_var_value) %>% dplyr::pull(title_start) %>% dplyr::first() title_end = df_config_gantt %>% dplyr::filter(input_var == input_var_value) %>% dplyr::pull(title_end) %>% dplyr::first() title = paste0(title_start, filter_value, title_end) ## TODO Functie ## dplyr::filter gantt based on selections df_gantt <- df %>% dplyr::filter(!!rlang::sym(input_var_value) == filter_value) %>% dplyr::group_by(!!rlang::sym(input_var_value), !!rlang::sym(split_var)) %>% dplyr::summarize(n = dplyr::n()) %>% dplyr::ungroup() %>% ## Zet rijen op volgorde en geef ze vervolgens begin en eind percentage de verschillende ## beginnen waar de ander stopt dplyr::arrange(dplyr::desc(n)) %>% dplyr::mutate( flow_perc = n / sum(n), flow_end_perc = cumsum(flow_perc), flow_start_perc = dplyr::lag(flow_end_perc), flow_start_perc = ifelse(is.na(flow_start_perc), 0, flow_start_perc) ) %>% ## Limit number of values limit_n_values_gantt(split_var) x <- "flow_start_perc" xend <- "flow_end_perc" gantt_plot(df_gantt, x, xend, split_var, title, position_label_y) }) }) } ## Limit number of values for Gantt chart ## ## This function limits the number of values displayed in a Gantt chart. If the number of distinct ## values in the specified variable is less than the limit, the function returns the original dataframe. ## ## @param df A dataframe to be processed ## @param split_var A character vector specifying the variable to be split ## @param n_values An integer specifying the maximum number of values (default is 12) ## ## @return A dataframe with a limited number of values for the Gantt chart limit_n_values_gantt <- function(df, split_var, n_values = 12) { split_var_placeholder <- NULL if (n_values >= dplyr::n_distinct(df[[split_var]])) { return(df) } values_to_keep <- df[[split_var]][1:(n_values - 1)] ## All variables from manipulation before gantt n <- sum(df$n[(n_values):nrow(df)]) flow_perc <- sum(df$flow_perc[n_values:nrow(df)]) flow_end_perc <- 1 flow_start_perc <- df$flow_start_perc[n_values] df_mutated <- df %>% dplyr::filter(!!rlang::sym(split_var) %in% values_to_keep) %>% dplyr::bind_rows(data.frame( # !!rlang::sym(split_var) := "other", split_var_placeholder = "Anders", n = n, flow_perc = flow_perc, flow_end_perc = flow_end_perc, flow_start_perc = flow_start_perc ) %>% ## Update the dataframe before binding to avoid multiple columns with same names dplyr::rename(!!rlang::sym(split_var) := split_var_placeholder)) %>% dplyr::arrange(flow_start_perc) return(df_mutated) } ## UI function for gantt chart module ## ## @param id Module id ## @param df_config_gantt Config data frame for gantt chart ## ## @return Shiny fluidPage UI module_gantt_ind_ui <- function(id, df_config_gantt) { ns <- shiny::NS(id) shiny::fluidPage( shiny::column( width = 12, shiny::fluidRow( shinydashboardPlus::box( width = 12, shinycssloaders::withSpinner( plotly::plotlyOutput(ns("gantt")), type = 4) ) ) ), shinydashboardPlus::dashboardSidebar( # TODO add filters shinydashboard::sidebarMenu( pickerGanttVar(id, "input_var", df_config_gantt), shiny::uiOutput(ns("filter_values")), shiny::uiOutput(ns("target_var")) ) ) ) }
/scratch/gouwar.j/cran-all/cranData/vvshiny/R/module_gantt.R
#' Bind both #' #' This function binds two dataframes row-wise and performs additional manipulations depending on the 'type'. #' The function also reorders the factor levels of the specified facet variable. #' #' @param dfLeft A dataframe to be combined #' @param dfRight A dataframe to be combined #' @param id An identifier string specifying the type of operation #' @param y_left A character vector specifying the column to be used for the left dataframe #' @param y_right A character vector specifying the column to be used for the right dataframe #' @param facet_var A symbol specifying the variable to be used for faceting #' @param facet_name_var A symbol specifying the variable to be used for the facet name #' #' @return A dataframe obtained by binding dfLeft and dfRight, with additional transformations applied #' @export #' @examples #' df1 <- data.frame(x = 1:5, y = rnorm(5), VIS_Groep_naam = "One") #' df2 <- data.frame(x = 6:10, y = rnorm(5), VIS_Groep_naam = "Two") #' df_both <- bind_both(df1, df2, id = "test", #' y_left = "y", y_right = "y", #' facet_var = rlang::sym("x")) bind_both <- function(dfLeft, dfRight, id = "bench", y_left = NULL, y_right = NULL, facet_var = rlang::sym("VIS_Groep"), facet_name_var = rlang::sym("VIS_Groep_naam")) { y <- NULL ## Binds the left and right dataframes and reorders factor levels dfBoth <- dplyr::bind_rows(dfLeft, dfRight) %>% dplyr::mutate(!!facet_name_var := forcats::fct_reorder(!!facet_name_var, !!facet_var, min)) # dplyr::mutate(VIS_Groep_naam = forcats::fct_reorder(VIS_Groep_naam, VIS_Groep, min)) ## Mutates y for comparison type if (stringr::str_detect(id, "comp")) { dfBoth <- dfBoth %>% dplyr::mutate(y = dplyr::if_else(!!facet_var == "left", !!rlang::sym(y_left), !!rlang::sym(y_right) )) } return(dfBoth) } #' Bind both table #' #' This function joins two summarized dataframes and relocates y_left before y_right. #' The function also sets the VIS_Groep value to 'left' for the right dataframe. #' #' @param dfLeft_summ A summarized dataframe to be joined #' @param dfRight_summ A summarized dataframe to be joined #' @param y_left A character vector specifying the column to be relocated before y_right #' @param y_right A character vector specifying the column after which y_left will be relocated #' #' @return A dataframe obtained by joining dfLeft_summ and dfRight_summ, with y_left relocated before y_right #' @export #' @examples #' df1 <- data.frame( #' VIS_Groep = "a", #' x = c("a", "b"), #' y1 = 1:2 #' ) #' df2 <- data.frame( #' VIS_Groep = "b", #' x = c("a", "b"), #' y2 = 3:4 #' ) #' #' df_both <- bind_both_table(df1, df2, "y1", "y2") #' bind_both_table <- function(dfLeft_summ, dfRight_summ, y_left, y_right) { ## Changes VIS_Groep to 'left' for the right summarized dataframe dfRight_summ <- dfRight_summ %>% dplyr::mutate(VIS_Groep = dplyr::first(dfLeft_summ$VIS_Groep)) ## Joins left and right summarized dataframes, and relocates y_left before y_right dfBoth <- dplyr::inner_join(dfLeft_summ, dfRight_summ) dfBoth_table <- dfBoth %>% dplyr::relocate(!!rlang::sym(y_left), .before = !!rlang::sym(y_right)) return(dfBoth_table) }
/scratch/gouwar.j/cran-all/cranData/vvshiny/R/server_bind.R
## Generate Javascript for datatable headers. ## ## This function generates Javascript code for datatable headers. The script adjusts header tooltips and names. ## The abbreviations have a minimum length of 7 characters. ## ## @param data An optional data.frame. Default is 'data' in the global environment. ## @return A character vector containing the JavaScript code. header_callback <- function(data = data) { ## De r code heeft geen toegang tot het data-object uit de Javascript functie. ## Voeg dit daarom toe als optionele variabele ## Zie comment bij: https://vustudentanalytics.atlassian.net/browse/VUSASOFT-3541 c( "function(thead, data, start, end, display){", " var ncols = data[0].length;", sprintf( " var shortnames = [%s]", paste0(paste0( "'", abbreviate(names(data), minlength = 7), "'" ), collapse = ",") ), sprintf( " var tooltips = [%s];", paste0(paste0( "'", names(data), "'" ), collapse = ",") ), " for(var i=0; i<ncols; i++){", " $('th:eq('+i+')',thead).attr('title', tooltips[i]).text(shortnames[i]);", " }", "}" ) } ## Generate Javascript for datatable cell values. ## ## This function generates Javascript code for datatable cell values. The script truncates cell values to 11 characters and adds a tooltip with the full value. ## ## @param data A data.frame. ## @return A character vector containing the JavaScript code. value_callback <- function(data) { ## Zie comment bij: https://vustudentanalytics.atlassian.net/browse/VUSASOFT-3541 c( "function(data, type, row, meta) {", "return type === 'display' && data.length > 11 ?", "'<span title=\"' + data + '\">' + data.substr(0, 9) + '...</span>' : data;", "}" ) } ## Add header-related Javascript to datatable options. ## ## This function takes a list of datatable options and adds the header-related Javascript from 'header_callback' to these options. ## ## @param options_DT A list of datatable options. ## @param data A data.frame. ## @return The updated list of datatable options. add_with_limit_header_JS <- function(options_DT, data) { headerJS <- list(headerCallback = htmlwidgets::JS(header_callback(data))) ## Add header code options_DT <- c(options_DT, headerJS) return(options_DT) } ## Add value-related Javascript to datatable options. ## ## This function takes a list of datatable options and adds the value-related Javascript from 'value_callback' to these options. ## ## @param options_DT A list of datatable options_DT. ## @param data A data.frame. ## @return The updated list of datatable options_DT. add_width_limit_values_JS <- function(options_DT, data) { valueJS <- list( targets = "_all", render = htmlwidgets::JS(value_callback(data)) ) ## Extract current columnDefs internal lists (if set) ## Add valueJS to it and set new ColumnDefs ## INFO Code is a bit complex, but this method ensures it works also when columnDefs aren't set new_columns_options_DT <- append(options_DT["columnDefs"] %>% unname() %>% rlang::flatten(), list(valueJS)) new_columns_options_DT <- stats::setNames(list(new_columns_options_DT), "columnDefs") options_DT["columnDefs"] <- new_columns_options_DT return(options_DT) } ## Get basic datatable options. ## ## This function returns a list of basic datatable options. ## ## @return A list of datatable options. basic_options <- function() { list( language = list(url = "//cdn.datatables.net/plug-ins/1.10.11/i18n/Dutch.json"), pagingType = "full", deferRender = TRUE, # dom = 'lfrti<"table-button"B>p', # dom = "<'table-button'B><lf><t><'row'<'col-sm-4'i><'col-sm-8'p>>", dom = "<'row'<'col-sm-6'l><'col-sm-6'f>><'row'<'col-sm-12'tr>><'row'<'col-sm-4'i><'col-sm-8'p>><'table-button paginate_button'B>", buttons = c("excel", "pdf", "print"), # info = TRUE, # processing = TRUE, columnDefs = list( list( targets = "_all", className = "dt-center" ) ) ) } ## Get advanced datatable options. ## ## This function returns a list of advanced datatable options. ## ## @return A list of datatable options. advanced_options <- function() { list( pagingType = "full", colReorder = TRUE, rowReorder = TRUE, deferRender = TRUE, lengthChange = TRUE, dom = 'lfrti<"table-button"B>p', scrollX = "362px", buttons = c("colvis", "copy", "csv"), info = TRUE, processing = TRUE, columnDefs = list( list( targets = "_all", className = "dt-center" ) ) ) } ## Create a basic datatable. ## ## This function creates a basic datatable with various configurable options and features. ## ## @param data The data.frame to be displayed. ## @param rownames A logical value indicating whether to display row names. ## @param extensions A character vector specifying the DataTables extensions to be used. ## @param options_DT A list of DataTables options. ## @param limit_width A character string indicating how to limit column width. ## @param ... Additional arguments passed to DT::datatable(). ## @return A datatable object. make_basic_table <- function(data, rownames = FALSE, extensions = c("Buttons"), options_DT = basic_options(), limit_width = "values", ...) { if (limit_width == "both") { ## set JS options_DT <- add_width_limit_values_JS(options_DT, data) options_DT <- add_with_limit_header_JS(options_DT) } else if (limit_width == "values") { options_DT <- add_width_limit_values_JS(options_DT, data) } else if (limit_width == "headers") { options_DT <- add_with_limit_header_JS(options_DT) } ## Add some basic logic if ("pageLength" %in% names(options_DT)) { # do nothing } else { if (nrow(data) <= 15) { options_DT <- c(options_DT, paging = FALSE) options_DT <- c(options_DT, info = FALSE) } } if ("searching" %in% names(options_DT)) { # do nothing } else { if (nrow(data) <= 15) { options_DT <- c(options_DT, searching = FALSE) } } if (nrow(data) > 15 & !("lengthChange" %in% options_DT)) { options_DT <- c(options_DT, list(lengthMenu = list( c(10, -1), c("10", "All") ))) } else { options_DT <- c(options_DT, lengthChange = FALSE) } DT::datatable(data, rownames = rownames, extensions = extensions, options = options_DT, ## Escape is always true for security reasons, see documentation escape = TRUE, style = "bootstrap", ... ) } ## Create an advanced datatable. ## ## This function creates an advanced datatable with various configurable options and features. ## ## @param data The data.frame to be displayed. ## @param rownames A logical value indicating whether to display row names. ## @param filter A character string indicating where to display the table filter. ## @param extensions A character vector specifying the DataTables extensions to be used. ## @param options_DT A list of DataTables options. ## @param limit_width A logical value indicating whether to limit column width. ## @param ... Additional arguments passed to DT::datatable(). ## @return A datatable object. make_advanced_table <- function( data, rownames = FALSE, filter = "top", extensions = c("Buttons", "ColReorder", "RowReorder"), options_DT = advanced_options(), limit_width = "values", ...) { if (limit_width == "both") { ## set JS options_DT <- add_width_limit_values_JS(options_DT, data) options_DT <- add_with_limit_header_JS(options_DT) } else if (limit_width == "values") { options_DT <- add_width_limit_values_JS(options_DT, data) } else if (limit_width == "headers") { options_DT <- add_with_limit_header_JS(options_DT) } ## Voeg All als optie lengte tabel toe if ("lengthMenu" %in% options_DT) { ## do nothing } else { options_DT <- c(options_DT, list(lengthMenu = list( c(10, 25, 50, 100, -1), c("10", "25", "50", "100", "All") ))) } if ("pageLength" %in% names(options_DT)) { # do nothing } else { if (nrow(data) <= 25) { options_DT <- c(options_DT, paging = FALSE) } } DT::datatable(data, rownames = rownames, extensions = extensions, filter = filter, options = options_DT, ## Escape is always true for security reasons, see documentation escape = TRUE, ... ) } ## Create a basic datatable for HTML rendering. ## ## This function creates a basic datatable with options optimized for HTML rendering. ## ## @param data The data.frame to be displayed. ## @param ... Additional arguments passed to 'make_basic_table()'. ## @return A datatable object. make_basic_table_html <- function(data, ...) { make_basic_table( data, width = "100%", height = "auto", options_DT = c(basic_options(), scrollX = TRUE), limit_width = NULL, ... ) } ## Create an advanced datatable for HTML rendering. ## ## This function creates an advanced datatable with options optimized for HTML rendering. ## ## @param data The data.frame to be displayed. ## @param ... Additional arguments passed to 'make_advanced_table()'. ## @return A datatable object. make_advanced_table_html <- function(data, ...) { make_advanced_table( data, width = "100%", height = "auto", options_DT = c(basic_options(), scrollX = TRUE), limit_width = NULL, ... ) } #' Prepare a data table for displaying #' #' This function prepares a data table for displaying by providing user-friendly names, removing unneeded variables, and formatting percentages. #' #' @param y A string specifying the column name to be used as the y-axis variable. #' @param df A data frame containing the raw data. #' @param df_summarized A data frame containing the summarized data. #' @param id A string specifying the ID associated with the data. #' @param y_right An optional string specifying the column name to be used as the second y-axis variable. Default is NULL. #' @param facet_var A symbol specifying the column to be used for faceting. Default is 'VIS_Groep'. #' @param facet_name_var A symbol specifying the column to be used for faceting names. Default is 'VIS_Groep_naam'. #' @param table_type Choose from basic for a simple datatable and advanced for more buttons etc. #' @param rownames A logical value indicating whether to display row names. #' @param extensions A character vector specifying the DataTables extensions to be used. #' @param options_DT A list of DataTables options. #' @param limit_width A character string indicating how to limit column width. #' @param ... Further arguments passed on to the 'make_basic_table' function. #' @return A DT::datatable object ready for displaying. #' @export #' @examples #'df <- data.frame(VIS_Groep = c("Group1", "Group1", "Group2", "Group2"), #' VIS_Groep_naam = c("Name1", "Name1", "Name2", "Name2"), #' y = c(TRUE, TRUE, FALSE, FALSE), z = c(TRUE, FALSE, TRUE, FALSE)) #'df_summarized <- df %>% #' dplyr::group_by(VIS_Groep, VIS_Groep_naam) %>% #' dplyr::summarise( #' y = mean(y), #' z = mean(z) #' ) %>% #' dplyr::ungroup() #' id <- "id" #'output <- prep_table("y", df, df_summarized, id = id) #' prep_table <- function(y, df, df_summarized, id, y_right = NULL, facet_var = rlang::sym("VIS_Groep"), facet_name_var = rlang::sym("VIS_Groep_naam"), table_type = c("basic", "advanced"), rownames = FALSE, extensions = c("Buttons"), options_DT = basic_options(), limit_width = "values", ...) { ## table type table_type <- dplyr::first(table_type) ## Remove unneeded variables dfTabel <- df_summarized %>% dplyr::select( -!!facet_name_var, -!!facet_var ) ## Set user friendly names names(dfTabel) <- purrr::map_chr(names(dfTabel), ~ display_name(.x, id)) ## Get boolean vars in order to add formatting % if (is.logical(df[[y]])) { sBoolean_vars <- y } else { sBoolean_vars <- c() } if (!is.null(y_right) && is.logical(df[[y_right]])) { sBoolean_vars <- c(sBoolean_vars, y_right) } sBoolean_vars <- sBoolean_vars %>% purrr::map_chr(~ display_name(.x, id)) if (table_type == "basic") { ## Make datatable object dfTabel <- dfTabel %>% make_basic_table( rownames = rownames, extensions = extensions, options_DT = options_DT, limit_width = limit_width, caption = dplyr::first(df_summarized[[facet_name_var]]), ... ) %>% DT::formatPercentage(sBoolean_vars, 2) } else { dfTabel <- dfTabel %>% make_advanced_table( rownames = rownames, extensions = extensions, options_DT = options_DT, limit_width = limit_width, caption = dplyr::first(df_summarized[[facet_name_var]]), ... ) %>% DT::formatPercentage(sBoolean_vars, 2) } return(dfTabel) }
/scratch/gouwar.j/cran-all/cranData/vvshiny/R/server_datatable.R
#' Prepare a dataframe #' #' Prepares a dataframe based on provided filters and naming options #' #' This function collapses values from the naming list into a single string, #' removes null elements from the filter list, transforms filter list into elements #' suitable for filtering, applies filters, adds new columns, and casts var used as color to factor. #' @param lFilters List of filters to be applied on the dataframe. #' @param lValues_for_naming List of values used for naming. #' @param df Dataframe to be processed. #' @param color_var Variable used for coloring. #' @param facet Facet grid side ("left" by default). #' @param facet_var Variable used for facet grid ("VIS_Groep" by default). #' @param facet_name_var Variable used for facet grid naming ("VIS_Groep_naam" by default). #' @return A prepared dataframe with applied filters and new columns. #' @export #' @examples #' df <- dplyr::tibble( #' VIS_Groep = sample(c("Group1", "Group2", "Group3"), 100, replace = TRUE), #' VIS_Groep_naam = sample(c("Name1", "Name2", "Name3"), 100, replace = TRUE), #' var1 = sample(c("A", "B", "C"), 100, replace = TRUE), #' var2 = rnorm(100), #' color_var = sample(c("Red", "Blue", "Green"), 100, replace = TRUE) #' ) #' lFilters <- list("A;var1") #' lValues_for_naming = list("Name1;VIS_Groep_naam", "Name2;VIS_Groep_naam") #' color_var = "color_var" #' dfPrepared <- prep_df(lFilters, lValues_for_naming, df, color_var, facet = "right") prep_df <- function(lFilters, lValues_for_naming, df, color_var, facet = "left", facet_var = rlang::sym("VIS_Groep"), facet_name_var = rlang::sym("VIS_Groep_naam")) { ## Collapses values from the naming list into a single string sName <- paste(keep_values(lValues_for_naming), collapse = " / ") ## Removes null elements from the filter list lFilters <- lFilters %>% purrr::discard(is.null) ## Transforms filter list into elements suitable for filtering lFilter_elements <- purrr::map(lFilters, transform_input) ## Applies filters, adds new columns, and casts var used as color to factor dfPrepared <- df %>% filter_with_lists(lFilter_elements) %>% dplyr::mutate( !!facet_var := facet, !!facet_name_var := paste("VU", sName, sep = " - " ) ) %>% dplyr::mutate(!!rlang::sym(color_var) := as.factor(!!rlang::sym(color_var))) return(dfPrepared) } #' Keep only relevant values #' #' Filters out only relevant values based on the provided filters #' #' This function removes null elements from the filter list, transforms filter list into elements #' suitable for filtering, and retrieves relevant values from the data. #' @param lFilters List of filters to be applied on the data. #' @param sVariable The variable for which relevant values are to be retrieved. #' @param dfFilters Dataframe with the possible filters and values for this dataset #' @return A list of relevant values for the specified variable. #' @export #' @examples #' dfFilters <- dplyr::tibble( #' var1 = sample(c("A", "B", "C"), 100, replace = TRUE), #' var2 = sample(c("D", "E", "F"), 100, replace = TRUE), #' var3 = sample(c("G", "H", "I"), 100, replace = TRUE) #' ) #' filters <- list("D;var2") #' relevant_values <- keep_only_relevant_values(filters, "var1", dfFilters) #' #' # Check if the relevant values are only from the rows where var2 is "D" or "E" #' expected_values <- dfFilters$var1[dfFilters$var2 %in% c("D")] %>% #' purrr::set_names(.) %>% #' purrr::map(~paste0(.x, ";var1")) keep_only_relevant_values <- function(lFilters, sVariable, dfFilters) { ## Verifies the input variables are set, if not stop execution shiny::req(lFilters) ## Removes null elements from the filter list lFilters <- lFilters %>% purrr::discard(is.null) ## Transforms filter list into elements suitable for filtering lFilter_elements <- purrr::map(lFilters, transform_input) ## Retrieves relevant values from the data lRelevant_values <- dfFilters %>% filter_with_lists(lFilter_elements) %>% dplyr::pull(!!rlang::sym(sVariable)) %>% purrr::set_names(.) %>% purrr::map(~ paste(.x, sVariable, sep = ";")) return(lRelevant_values) } #' Keep values #' #' This function extracts values before the semicolon from a ";"-separated string. #' #' @param input A character vector with ";"-separated strings #' #' @return A list of values before the semicolon in the input #' @export #' @examples #' input = c("A;var1", "B;var1", "C;var1") #' values = keep_values(input) keep_values <- function(input) { lValues <- purrr::map(input, ~ stringr::str_split(., ";")[[1]][1]) return(lValues) } #' Transform input #' #' This function transforms a list of inputs into a column and value for filtering. #' #' @param input A list of inputs to be transformed #' #' @return A list containing a column and its corresponding value for filtering #' @export #' @examples #' input = list("A;var1", "B;var1", "C;var1") #' filter_element = transform_input(input) transform_input <- function(input) { ## Splits the string and retrieves the second part as the column name sColumn <- stringr::str_split(input[1], ";")[[1]][2] ## Retrieves the filter values lValues <- keep_values(input) ## Combines column and values into a filter element lFilter_element <- list(sColumn, lValues) return(lFilter_element) } #' Filter with lists #' #' This function filters a dataframe using a list with column and one or more values. #' #' @param df A dataframe to be filtered #' @param filters A list of lists containing column names in the first element and a list their #' corresponding values for filtering in the second element #' #' @return A dataframe filtered based on the input filters #' @export #' @examples #' df <- dplyr::tibble( #' VIS_Groep = sample(c("Group1", "Group2", "Group3"), 100, replace = TRUE), #' VIS_Groep_naam = sample(c("Name1", "Name2", "Name3"), 100, replace = TRUE), #' var1 = sample(c("A", "B", "C"), 100, replace = TRUE), #' var2 = rnorm(100), #' color_var = sample(c("Red", "Blue", "Green"), 100, replace = TRUE) #' ) #' filters = list(c("var1", c("A", "B"))) #' dfFiltered <- filter_with_lists(df, filters) filter_with_lists <- function(df, filters) { ## Applies each filter to the dataframe df <- purrr::reduce(filters, function(df, filter) { df %>% dplyr::filter(!!rlang::sym(filter[[1]]) %in% unlist(filter[[2]])) }, .init = df) return(df) }
/scratch/gouwar.j/cran-all/cranData/vvshiny/R/server_filters.R
#' Wrapped chart #' #' Wrapped chart function for creating a plot based on the provided dataframe and variables. #' #' @param df The data frame used to create the plot. #' @param x The variable used on the x-axis of the plot. #' @param y The variable used on the y-axis of the plot. #' @param color The variable used to color the points or bars in the plot. #' @param id The identifier for selecting the data frame source. #' @param df_original The original dataframe before summarization #' @param y_left The variable used on the left y-axis when creating a comparative plot. #' @param y_right The variable used on the right y-axis when creating a comparative plot. #' @param facet_var The variable used for facet wrapping. #' @param facet_name_var The name of the variable used for facet wrapping. #' #' @return A ggplot object. wrapped_chart <- function(df, x, y, color, id = "bench", df_original, y_left = NULL, y_right = NULL, facet_var = rlang::sym("VIS_Groep"), facet_name_var = rlang::sym("VIS_Groep_naam")) { ## Depending on the type of plot, set facet wrap and labels settings if (stringr::str_detect(id, "bench")) { facet_wrap_setting <- ggplot2::facet_wrap(ggplot2::vars(!!facet_name_var)) xlab_setting <- ggplot2::xlab(display_name(x, id)) ylab_setting <- ggplot2::ylab(display_name(y, id)) ## Get boolean vars in order to add formatting % if (is.logical(df_original[[y]])) { scale_y <- ggplot2::scale_y_continuous(labels = scales::percent) } else { scale_y <- ggplot2::scale_y_continuous() } } else if (stringr::str_detect(id, "comp")) { if (is.logical(df_original[[y_left]]) && is.logical(df_original[[y_right]])) { scale_y <- ggplot2::scale_y_continuous(labels = scales::percent) } else { scale_y <- ggplot2::scale_y_continuous() } facet_wrap_setting <- ggplot2::facet_wrap(ggplot2::vars(!!facet_var), scales = "free_y", labeller = ggplot2::as_labeller(c( "left" = display_name(y_left, id), "right" = display_name(y_right, id) )) ) xlab_setting <- ggplot2::xlab(NULL) ylab_setting <- ggplot2::ylab(NULL) } ## Create the base plot plot <- basic_plot(df, x, y, color, xlab_setting, ylab_setting, ggplot_basic_settings(), "top", scale_y) + facet_wrap_setting ## Set plot type based on the nature of x if (is.numeric(df[[x]]) && length(unique(df[[x]])) > 1) { plot <- plot + ggplot2::geom_line(ggplot2::aes(color = !!rlang::sym(color))) + ggplot2::geom_point(ggplot2::aes(color = !!rlang::sym(color))) + ggplot2::scale_x_continuous( labels = scales::label_comma(accuracy = 1), n.breaks = length(unique(df[[x]])) ) ## Set breaks instead of n_breaks when there is only value in numeric variable } else if (is.numeric(df[[x]])) { plot <- plot + ggplot2::geom_bar(position = "dodge", stat = "identity") + ggplot2::scale_x_continuous( labels = scales::label_comma(accuracy = 1), breaks = unique(df[[x]]) ) } else { plot <- plot + ggplot2::geom_bar(position = "dodge", stat = "identity") } ## Add legend using ggplotly plot <- ggplotly_with_legend(plot, color, id) return(plot) } #' Stacked bar chart #' #' Create a stacked bar chart, with optional settings for percentage (or not) and wrap (or not) modes. #' #' @param df The data frame used to create the plot. #' @param x The variable used on the x-axis of the plot. #' @param color The variable used to color the points or bars in the plot. #' @param id The identifier for selecting the data frame source. #' @param facet_name_var The name of the variable used for facet wrapping. #' @param percentage Logical indicating whether to create a plot in percentage mode. #' @param wrap Logical indicating whether to use facet wrapping. #' #' @return A ggplot object. stacked_composition_bar_chart <- function(df, x, color, id, facet_name_var = rlang::sym("VIS_Groep_naam"), percentage = FALSE, wrap = FALSE) { Aantal <- NULL ## Set plot type and y-axis label depending on whether plot is in percentage mode if (percentage == TRUE) { position <- "fill" y <- "Percentage" scale_y <- ggplot2::scale_y_continuous(labels = scales::percent) df <- df %>% dplyr::rename(Percentage = Aantal) } else { position <- "stack" y <- "Aantal" scale_y <- ggplot2::scale_y_continuous() } xlab_setting <- ggplot2::xlab(display_name(x, id)) ylab_setting <- ggplot2::ylab(y) ## Create the base plot plot <- basic_plot(df, x, y, color, xlab_setting, ylab_setting, ggplot_basic_settings()) + ggplot2::geom_bar(position = position, stat = "identity") + scale_y if (is.numeric(df[[x]]) && length(unique(df[[x]])) > 1) { plot <- plot + ggplot2::scale_x_continuous( labels = scales::label_comma(accuracy = 1), n.breaks = length(unique(df[[x]])) ) } else if (is.numeric(df[[x]])) { plot <- plot + ggplot2::scale_x_continuous( labels = scales::label_comma(accuracy = 1), breaks = unique(df[[x]]) ) } if (wrap == TRUE) { plot <- plot + ggplot2::facet_wrap(ggplot2::vars(!!facet_name_var)) } plot <- plotly::ggplotly(plot) return(plot) } #' Grid boxplot #' #' Function for creating grid boxplots for either benchmark or comparison across variables. #' #' @param df The data frame used to create the plot. #' @param x The variable used on the x-axis of the plot. #' @param color The variable used to color the points or bars in the plot. #' @param y The variable used on the y-axis of the plot. #' @param id The identifier for selecting the data frame source. #' @param y_left The variable used on the left y-axis when creating a comparative plot. #' @param y_right The variable used on the right y-axis when creating a comparative plot. #' @param facet_var The variable used for facet wrapping. #' @param facet_name_var The name of the variable used for facet wrapping. #' #' @return A ggplot object. grid_boxplots <- function(df, x, color, y, id, y_left = NULL, y_right = NULL, facet_var = rlang::sym("VIS_Groep"), facet_name_var = rlang::sym("VIS_Groep_naam")) { df <- df %>% dplyr::arrange(!!rlang::sym(color), !!rlang::sym(x)) %>% dplyr::mutate(!!rlang::sym(y) := as.numeric(!!rlang::sym(y))) unique_values_x <- unique(df[[x]]) n_rows_grid <- length(unique_values_x) ## Set the facet grid and labels settings depending on the type of plot if (stringr::str_detect(id, "bench")) { facet_grid_setting <- ggplot2::facet_grid( rows = ggplot2::vars(!!rlang::sym(x)), cols = ggplot2::vars(!!facet_name_var) ) xlab_setting <- ggplot2::xlab(display_name(x, id)) ylab_setting <- ggplot2::ylab(display_name(y, id)) ## Create base plot plot <- basic_plot(df, color, y, color, xlab_setting, ylab_setting, ggplot_basic_settings()) + ggplot2::geom_boxplot() + facet_grid_setting plot <- plotly::ggplotly(plot, height = 250 * n_rows_grid) } else if (stringr::str_detect(id, "comp")) { xlab_setting <- ggplot2::xlab(NULL) ylab_setting <- ggplot2::ylab(NULL) plot_list <- list() ## Create a plot for each unique value of x for (value_x in (unique_values_x)) { ## Filter only for this value of x df_part <- df %>% dplyr::filter(!!rlang::sym(x) == value_x) ## Set labels dynamic as names for facet_var since labeller() function doesn't accept ## Non Standard Evaluation (i.e. use of !!) labels_facet_var <- stats::setNames( list(c( "left" = paste(display_name(y_left, id), value_x, sep = " - "), "right" = paste(display_name(y_right, id), value_x, sep = " - ") )), as.character(facet_var) ) facet_grid_setting <- ggplot2::facet_wrap( ggplot2::vars(!!facet_var), scales = "free_y", labeller = ggplot2::labeller(!!!labels_facet_var) ) scale_x <- ggplot2::scale_x_discrete() ## Create base plot subplot <- basic_plot( df_part, color, y, color, xlab_setting, ylab_setting, ggplot_basic_settings() ) + ggplot2::geom_boxplot() + facet_grid_setting + scale_x + ggplot2::scale_y_continuous( labels = scales::label_number(accuracy = 0.1) ) ## Ggplot object is itself a list. Wrap this in a list to get a list with ggplot list objects plot_list <- append(plot_list, list(subplot)) } plot_list <- purrr::map(plot_list, ~ plotly::ggplotly(.x, height = 250 * n_rows_grid)) plot <- plotly::subplot(plot_list, nrows = n_rows_grid) } return(plot) } #' Grid histogram #' #' Function for creating grid histograms. #' #' @param df The data frame used to create the plot. #' @param x The variable used on the x-axis of the plot. #' @param color The variable used to color the points or bars in the plot. #' @param y The variable used on the y-axis of the plot. #' @param id The identifier for selecting the data frame source. #' @param y_left The variable used on the left y-axis when creating a comparative plot. #' @param y_right The variable used on the right y-axis when creating a comparative plot. #' @param facet_var The variable used for facet wrapping. #' @param facet_name_var The name of the variable used for facet wrapping. #' #' @return A list of ggplot objects. grid_histograms <- function(df, x, color, y, id, y_left = NULL, y_right = NULL, facet_var = rlang::sym("VIS_Groep"), facet_name_var = rlang::sym("VIS_Groep_naam")) { width <- density <- NULL df <- df %>% dplyr::mutate(!!rlang::sym(y) := as.numeric(!!rlang::sym(y))) unique_values_x <- unique(df[[x]]) n_rows_grid <- length(unique_values_x) ylab_setting <- ggplot2::ylab(NULL) scale_y <- ggplot2::scale_y_continuous(labels = scales::percent) scale_x <- ggplot2::scale_x_continuous() # limits = c(min(df[[y]], na.rm = TRUE), max(df[[y]], na.rm = TRUE))) ## Set the facet grid and labels settings depending on the type of plot if (stringr::str_detect(id, "bench")) { xlab_setting <- ggplot2::xlab(display_name(y, id)) facet_grid_setting <- ggplot2::facet_grid( rows = ggplot2::vars(!!rlang::sym(x)), cols = ggplot2::vars(!!facet_name_var) ) ## Create base plot plot <- basic_plot(df, y, y, color, xlab_setting, ylab_setting, ggplot_basic_settings()) + ggplot2::geom_histogram( position = "identity", ## The bar overlap so alpha is needed to see through alpha = 0.5, ggplot2::aes(color = !!rlang::sym(color), y = ggplot2::stat(width * density)) ) + facet_grid_setting + scale_y + scale_x ## Make plotly with appropriate height and put it in list for further usage plot <- plotly::ggplotly(plot, height = 250 * n_rows_grid) plot_list <- list(plot) } else if (stringr::str_detect(id, "comp")) { xlab_setting <- ggplot2::xlab(NULL) plot_list <- list() ## Create a plot for each unique value of x for (value_x in (unique_values_x)) { ## Filter only for this value of x df_part <- df %>% dplyr::filter(!!rlang::sym(x) == value_x) ## Set labels dynamic as names for facet_var since labeller() function doesn't accept ## Non Standard Evaluation (i.e. use of !!) labels_facet_var <- stats::setNames( list(c( "left" = paste(display_name(y_left, id), value_x, sep = " - "), "right" = paste(display_name(y_right, id), value_x, sep = " - ") )), as.character(facet_var) ) facet_grid_setting <- ggplot2::facet_wrap( ggplot2::vars(!!facet_var), scales = "free_x", labeller = ggplot2::labeller(!!!labels_facet_var) ) ## Create base plot subplot <- basic_plot(df_part, y, y, color, xlab_setting, ylab_setting, ggplot_basic_settings()) + ggplot2::geom_histogram( position = "identity", ## The bar overlap so alpha is needed to see through alpha = 0.5, ggplot2::aes(color = !!rlang::sym(color), y = ggplot2::stat(width * density)) ) + facet_grid_setting + scale_y + scale_x ## Ggplot object is itself a list. Wrap this in a list to get a list with ggplot list objects plot_list <- append(plot_list, list(subplot)) } ## Make plotlys of all the ggplots and add total height plot_list <- purrr::map(plot_list, ~ plotly::ggplotly(.x, height = 250)) } return(plot_list) } #' Create a Gantt plot using ggplot and plotly #' #' This function creates a Gantt plot with the help of ggplot and plotly. #' #' @param df A data frame containing the data to be plotted. #' @param x A string specifying the column name to be used as the x-axis variable. #' @param xend A string specifying the column name to be used as the end of the x-axis variable. #' @param split_var A string specifying the column name to be used as the splitting variable. #' @param title A string specifying the title of the plot. #' @param position_label_y A string specifying the position of y-axis labels. #' @return A Gantt plot. gantt_plot <- function(df, x, xend, split_var, title, position_label_y) { plot <- ggplot2::ggplot( df, ggplot2::aes( x = !!rlang::sym(x), xend = !!rlang::sym(xend), # y = !!rlang::sym(split_var), # yend = !!rlang::sym(split_var), y = stats::reorder(!!rlang::sym(split_var), !!rlang::sym(x), decreasing = TRUE), yend = stats::reorder(!!rlang::sym(split_var), !!rlang::sym(x), decreasing = TRUE), color = !!rlang::sym(split_var) ) ) + ## worden. Dit kan worden getest door de 'plots' pane groter / kleine te maken ggplot2::geom_segment(size = 6) + ggpubr::theme_pubr() + # ggplot_basic_settings() + ggplot2::theme(legend.position = "none") + ggplot2::labs(x = NULL, y = NULL) + ggplot2::scale_x_continuous(labels = scales::label_percent()) + ggplot2::ggtitle(title) + ## Daarom extra plotly layout code toegevoegd ggplot2::scale_y_discrete(position = position_label_y) if (!requireNamespace("RColorBrewer", quietly = TRUE)) { rlang::inform("When the package RColorBrewer is installed, brewer palette Set3 is used") } plot <- plot + ggplot2::scale_color_manual(values = RColorBrewer::brewer.pal(name = "Set3", n = nrow(df)) %>% purrr::set_names(df[[split_var]])) plotly::ggplotly(plot) %>% plotly::layout( yaxis = list(side = position_label_y), legend = list( # orientation = "h", # xanchor = "center", # x = 0.5, # y = 1.20, title = title ) ) } #' Create a Sankey plot using ggplot and ggalluvial #' #' This function creates a Sankey plot with the help of ggplot and ggalluvial. #' #' @param df A data frame containing the data to be plotted. #' @param left_var A string specifying the column name to be used as the left variable. #' @param right_var A string specifying the column name to be used as the right variable. #' @param xlab_setting ggplot labels settings for x axes. #' @param ylab_setting ggplot labels settings for y axes. #' @param name_left A string specifying the name for the left side of the plot. #' @param name_right A string specifying the name for the right side of the plot. #' @param title A string specifying the title of the plot. #' @param title_size Numeric value specifying the size of the title. #' @param title_font A string specifying the font of the title. #' @return A Sankey plot. sankey_plot <- function(df, left_var, right_var, xlab_setting, ylab_setting, name_left, name_right, title, title_size = 20, title_font = "verdana") { n <- stratum <- NULL ggplot2::ggplot( data = df, ggplot2::aes( axis1 = !!rlang::sym(left_var), axis2 = !!rlang::sym(right_var), y = n ) ) + ggplot2::scale_x_discrete(limits = c(name_left, name_right), expand = c(.2, .05)) + xlab_setting + ylab_setting + ggplot2::scale_fill_brewer(palette = "Set3") + ggalluvial::geom_alluvium(ggplot2::aes(fill = c(!!rlang::sym(left_var))), alpha = 0.75, width = 1 / 8) + ggalluvial::geom_stratum(na.rm = FALSE, alpha = 1, width = 1 / 8) + ggplot2::geom_text(stat = "stratum", ggplot2::aes(label = ggplot2::after_stat(stratum))) + ggpubr::theme_pubr() + ggplot2::theme(plot.title = ggplot2::element_text(size = title_size, family = "verdana")) + ggplot2::ggtitle(title) + ggplot2::guides(fill = "none") } #' Set ggplot basic settings #' #' Basic ggplot settings are put in a list and returned #' #' @return A list with ggplot settings ggplot_basic_settings <- function() { settings <- list(ggplot2::scale_fill_brewer(palette = "Pastel1"), ggplot2::scale_colour_brewer(palette = "Pastel1")) return(settings) } #' Create a basic plot using ggplot #' #' This function creates a basic plot with the help of ggplot. #' #' @param df A data frame containing the data to be plotted. #' @param x A string specifying the column name to be used as the x-axis variable. #' @param y A string specifying the column name to be used as the y-axis variable. #' @param color A string specifying the column name to be used as the fill variable. #' @param xlab_setting ggplot labels settings for x axes. #' @param ylab_setting ggplot labels settings for y axes. #' @param ggplot_settings Additional settings for the ggplot. #' @param legend_position A string specifying the position of the legend. #' @param scale_y Optional ggplot2 scale function to modify the y axis. #' @return A ggplot plot. #' @export #' @examples #' df <- data.frame(x_var = rnorm(100), #' y_var = rnorm(100), #' color_var = sample(c("Red", "Blue"), #' 100, #' replace = TRUE)) #' xlab_setting <- ggplot2::xlab("x label") #' ylab_setting <- ggplot2::ylab("y label") #' ggplot_instellingen <- ggplot2::geom_point() #' scale_y <- ggplot2::scale_y_continuous() #' basic_plot(df, "x_var", "y_var", "color_var", xlab_setting, #' ylab_setting, ggplot_instellingen, "none", scale_y) basic_plot <- function(df, x, y, color, xlab_setting, ylab_setting, ggplot_settings = ggplot_basic_settings(), legend_position = "none", scale_y = NULL) { plot <- ggplot2::ggplot( df, ggplot2::aes( x = !!rlang::sym(x), y = !!rlang::sym(y), fill = !!rlang::sym(color) ) ) + ggpubr::theme_pubr() + ggplot_settings + xlab_setting + ylab_setting + ggplot2::theme(legend.position = legend_position) if (!is.null(scale_y)) { plot <- plot + scale_y } return(plot) }
/scratch/gouwar.j/cran-all/cranData/vvshiny/R/server_ggplot.R
#' Get a user-friendly display name #' #' This function provides a user-friendly name for a column based on a mapping table, if available. #' #' @param col_name A string specifying the name of the column. #' @param mapping_table A named list with as name the original colum name and as value the display #' name #' @return A string containing the user-friendly name for the column. #' @export #' @examples #' mapping <- list( #' col1 = "Column 1", #' col2 = "Column 2" #' ) #' display_name("col1", mapping) display_name <- function(col_name, mapping_table) { if (col_name %in% names(mapping_table)) { col_name <- mapping_table[[col_name]] } return(col_name) } #' Quietly run a function #' #' This function is a wrapper that allows a function to be run quietly without the need to create a separate quiet function. #' #' @param func The function to be run. #' @param ... Optional further arguments passed to the 'func' function. #' @return The list result of the 'func' function with messages, warnings, and output captured. #' @export #' @examples #' warning_func_arugment <- function(info) { #' warning(info) #' return("Complete") #' } #' result <- quietly_run(warning_func_arugment, "Just checking") quietly_run <- function(func, ...) { args <- list(...) quietly_func <- purrr::quietly(func) if(length(args) == 0) { # No arguments passed, just call func() quietly_func() } else { quietly_func(...) } }
/scratch/gouwar.j/cran-all/cranData/vvshiny/R/server_misc.R
#' Make ggplotly and add legend with color as title #' #' This function creates a Plotly version of a ggplot2 object and adds a legend with the user-friendly name of the color variable as its title. #' #' @param plot A ggplot object. #' @param color A string specifying the column name to be used as the color variable. #' @param mapping_table A named list with as name the original colum name and as value the display #' name #' @return A plotly object with a formatted legend. #' @export #' @examples #' df <- data.frame(x_var = rnorm(100), #' y_var = rnorm(100), #' color_var = sample(c("Red", "Blue"), #' 100, #' replace = TRUE)) #' xlab_setting <- ggplot2::xlab("x label") #' ylab_setting <- ggplot2::ylab("y label") #' ggplot_instellingen <- ggplot2::geom_point() #' scale_y <- ggplot2::scale_y_continuous() #' plot <- basic_plot(df, "x_var", "y_var", "color_var", xlab_setting, #' ylab_setting, ggplot_instellingen, "none", scale_y) #' mapping_table <- list(color_var = "user friendly name var") #' plotly_object <- ggplotly_with_legend(plot, "color_var", mapping_table) ggplotly_with_legend <- function(plot, color, mapping_table) { plot <- plotly::ggplotly(plot) %>% plotly::layout( legend = list( orientation = "h", xanchor = "center", x = 0.5, y = 1.20, title = list(text = display_name(color, mapping_table)) ) ) plot <- clean_pltly_legend(plot) return(plot) } #' Clean the legend of a plotly object #' #' This function cleans the legend of a plotly object by removing unnecessary duplication. #' It is specifically designed to work around a bug that causes facet_wrap to create a separate legend entry for each facet. #' #' @param pltly_obj A plotly object with a legend to be cleaned. #' @param new_legend An optional vector of strings specifying new legend entries. Default is an empty vector. #' @return The input plotly object with its legend cleaned. clean_pltly_legend <- function(pltly_obj, new_legend = c()) { ## Assigns a legend group from the list of possible entries assign_leg_grp <- function(legend_group, leg_nms) { leg_nms_rem <- leg_nms ## Assigns a .leg_name, if possible ## leg_options is a 2-element list: 1 = original value; 2 = remaining options parse_leg_nms <- function(leg_options) { ## No more legend names to assign if (is.na(leg_options)) { leg_options } else if (length(leg_nms_rem) == 0) { leg_options } else { ## Transfer the first element of the remaining options leg_nm_new <- leg_nms_rem[[1]] leg_nms_rem <<- leg_nms_rem[-1] leg_nm_new } } legend_group %>% purrr::map(~ parse_leg_nms(.)) } ## Simplifies legend groups by removing brackets, position numbers and then de-duplicating simplify_leg_grps <- function(legendgroup_vec) { leg_grp_cln <- purrr::map_chr(legendgroup_vec, ~ stringr::str_replace_all(., c("^\\(" = "", ",\\d+\\)$" = ""))) purrr::modify_if(leg_grp_cln, duplicated(leg_grp_cln), ~NA_character_) } pltly_obj_data <- pltly_obj$x$data ## pltly_leg_grp is a character vector where each element represents a legend group. Element is NA ## if legend group not required or doesn't exist pltly_leg_grp <- pltly_obj_data %>% purrr::map(~ purrr::pluck(., "legendgroup")) %>% ## Elements where showlegend = FALSE have legendgroup = NULL purrr::map_chr(~ if (is.null(.)) { NA_character_ } else { . }) %>% simplify_leg_grps() %>% assign_leg_grp(new_legend) pltly_obj_data_new <- pltly_obj_data %>% purrr::map2(pltly_leg_grp, ~ purrr::list_modify(.x, legendgroup = .y)) %>% purrr::map2(pltly_leg_grp, ~ purrr::list_modify(.x, name = .y)) %>% ## Set show legend FALSE when there is no legend purrr::map2(pltly_leg_grp, ~ purrr::list_modify(.x, showlegend = !is.na(.y))) ## Update orginal plotly object pltly_obj$x$data <- pltly_obj_data_new return(pltly_obj) }
/scratch/gouwar.j/cran-all/cranData/vvshiny/R/server_plotly.R
#' Prepare summarized dataframe #' #' This function prepares a summarized dataframe based on provided variables and a y-variable. #' The function groups the dataframe by the provided variables, summarizes the y-variable, #' and counts the number of observations per group. #' #' @param df A dataframe to be summarized #' @param variables A character vector specifying the columns to be grouped by #' @param y A character vector specifying the column to be summarized #' #' @return A summarized dataframe #' @export #' @examples #' df <- data.frame( #' id = c(1, 1, 2, 2), #' group = c("A", "A", "B", "B"), #' value = c(2, 4, 6, 8) #' ) #' df_summ <- prep_df_summ(df, c("id", "group"), "value") prep_df_summ <- function(df, variables, y) { ## Groups by provided variables, summarizes the y-variable and counts number of observations ## per group df_summarized <- df %>% dplyr::group_by(dplyr::across(dplyr::all_of(variables))) %>% dplyr::summarize( !!rlang::sym(y) := ifelse(y == "Geen", NA, round(mean(!!rlang::sym(y), na.rm = TRUE), 3) ), Aantal = dplyr::n() ) %>% dplyr::ungroup() return(df_summarized) } #' Prepare summarized and aggregated dataframe #' #' This function prepares a summarized dataframe based on provided variables, y-variable, #' color, and total count. The function groups the dataframe by the provided variables, #' calculates the weighted mean for the y-variable, sums up total count per group, and arranges by color. #' #' @param df A dataframe to be summarized #' @param variables A character vector specifying the columns to be grouped by #' @param y A character vector specifying the column to be summarized #' @param color A character vector specifying the column to be used for color arrangement #' @param total_n_var A symbol specifying the variable to be used for total count calculation #' @param aggr_split_value_var A symbol specifying the variable to be used for color assignment #' #' @return A summarized and aggregated dataframe arranged by color #' @export #' @examples #' df <- data.frame( split_var_value = c("male", "male", "female", "female", "dutch", "dutch", #' "EER", "EER", "Outside EER", "Outside EER"), other_var = c("Early", "Late", "Early", "Late", #' "Early", "Late", "Early", "Late", "Early", "Late"), value = c(2, 4, 6, 8, 10, 2, 4, 6, 8, 10), #' total = c(10, 10, 20, 20, 30, 30, 40, 40, 50, 50), split_var = c("gender", "gender", "gender", #' "gender", "background", "background", "background", "background", "background", "background") ) prep_df_summ_aggr <- function(df, variables, y, color, total_n_var = rlang::sym("INS_Aantal_eerstejaars"), aggr_split_value_var = rlang::sym("INS_Splits_variabele_waarde")) { ## Groups by provided variables, calculates weighted mean for y-variable, sums up total count per group and arranges by color variables <- unique(c(variables, rlang::as_name(aggr_split_value_var))) df_summarized <- df %>% dplyr::group_by(dplyr::across(dplyr::all_of(variables))) %>% dplyr::summarize( # !!rlang::sym(input$y_left) := round( # sum(!!rlang::sym(input$y_left), na.rm = TRUE) / sum(!!total_n_var, na.rm = TRUE), # 3), ## Calculates weighted average !!rlang::sym(y) := round( sum( (!!rlang::sym(y) * !!total_n_var), na.rm = TRUE ) / sum(!!total_n_var, na.rm = TRUE), 3 ), Aantal = sum(!!total_n_var) ) %>% dplyr::ungroup() %>% ## Set splits_variable_value to color, then set color in front and order on it so all the ## graphs and tables will be drawn correctly dplyr::mutate(!!rlang::sym(color) := !!aggr_split_value_var) %>% dplyr::select(-!!aggr_split_value_var) %>% dplyr::select(!!rlang::sym(color), dplyr::everything()) %>% dplyr::arrange(!!rlang::sym(color)) return(df_summarized) }
/scratch/gouwar.j/cran-all/cranData/vvshiny/R/server_prep.R
#' UI function for single module dashboard #' #' @param request shiny request object #' @param id Module id #' @param tab_item Tab item UI #' #' @return dashboardPage UI single_module_ui <- function(request, id, tab_item) { DB_header <- shinydashboardPlus::dashboardHeader( title = id ) DB_sidebar <- shinydashboardPlus::dashboardSidebar( shinydashboard::sidebarMenu( id = "tablist", shinydashboard::menuItem(id, tabName = id, selected = TRUE) ) ) DB_body <- shinydashboard::dashboardBody( htmltools::tags$script(src = "https://kit.fontawesome.com/01cb805c1e.js"), shinydashboard::tabItems( tab_item ) ) if (!requireNamespace("waiter", quietly = TRUE)) { rlang::inform("Install the waiter package to get a spinner for loading") shinydashboardPlus::dashboardPage( DB_header, DB_sidebar, DB_body#, #DB_rightsidebar, #freshTheme = NCO_theme, #preloader = list( # html = htmltools::tagList(waiter::spin_1(), "Loading ..."), # color = "#367fa9" #) ) } else { shinydashboardPlus::dashboardPage( DB_header, DB_sidebar, DB_body, #DB_rightsidebar, #freshTheme = NCO_theme, preloader = list( html = htmltools::tagList(waiter::spin_1(), "Loading ..."), color = "#367fa9" ) ) } }
/scratch/gouwar.j/cran-all/cranData/vvshiny/R/ui_general.R
#' @title pickerVar function #' @description Function to generate a picker input element based on given id and element. #' @param id A string representing the id of the input element. #' @param element A string representing the element. #' @param df_categories A dataframe with metadata about the available categories per picker element #' @param label A string representing the label of the input. Default is NULL. #' @return A pickerInput object. pickerVar <- function(id, element, df_categories, label = NULL) { Categorie <- NULL id_element <- shiny::NS(id, element) ## Select desired variables for the selection element based on metadata and presence in df lVariables <- df_categories %>% dplyr::filter(!is.na(!!rlang::sym(id_element))) %>% dplyr::arrange(!!rlang::sym(id_element)) %>% ## set Categorie based upon the order in the id_element column ## Zie: https://stackoverflow.com/a/61503816/6375668 dplyr::mutate(Categorie = stats::reorder(factor(Categorie), !!rlang::sym(id_element))) %>% ## Get variables and put them in named list per category dplyr::group_split(Categorie) %>% purrr::set_names(purrr::map_chr(., ~ .x$Categorie[1] %>% as.character())) %>% purrr::map(~ .x %>% dplyr::pull(Veldnaam) %>% as.list()) %>% ## Iterate over elements purrr::map( ~ purrr::map( ## check if element is present and correctly formed .x, ~ purrr::keep(.x, present_and_correct(.x, element, df = df)) %>% ## set the display name per element purrr::set_names(display_name(.x, id)) ## Remove all empty elements ) %>% purrr::compact() %>% unlist() ) ## Set the selected value based on the element if (element == "y_rechts") { selected <- lVariables[[1]][[2]] } else { selected <- lVariables[[1]][[1]] } if (is.null(label)) { label <- stringr::str_to_title(element) } shinyWidgets::pickerInput( inputId = id_element, label = label, choices = lVariables, selected = selected, options = list(`live-search` = TRUE) ) } #' @title pickerSplitVar function #' @description Function to create a picker input for splitting variables. #' @param id A string representing the id of the input element. #' @param variable A string representing the variable to split. Default is "INS_Splits_variabele". #' @param name A string representing the name. Default is "color". #' @param label A string representing the label of the input. Default is "Kleur". #' @param df A data frame containing the data. Default is dfCombi_geaggregeerd. #' @return A pickerInput object. pickerSplitVar <- function(id, variable = "INS_Splits_variabele", name = "color", label = "Kleur", df) { ## Create a named list with unique values as names and the combination of unique value and column name as value choices <- sort(unique(df[[variable]])) %>% purrr::discard(~ .x == "Alle") %>% purrr::map(~ paste(.x, variable, sep = ";")) %>% purrr::set_names(~ map_chr(.x, ~ display_name(.x, id))) inputId <- paste(id, name, sep = "-") shinyWidgets::pickerInput( inputId = inputId, label = label, choices = choices, options = list( `live-search` = TRUE ) ) } #' @title pickerValues function #' @description Function to create a picker input for filtering value. #' @param id A string representing the id of the input element. #' @param df A data frame containing the data. #' @param variable A string representing the variable to filter. Default is "faculty". #' @param role A string representing the role. Default is "left". #' @param selected The selected value. Default is "All". #' @param multiple A boolean indicating whether multiple selections are allowed. Default is TRUE. #' @return A pickerInput object. pickerValues <- function(id, df, variable = "faculty", role = "left", selected = "All", multiple = TRUE) { ns <- shiny::NS(id) inputId <- ns(paste(variable, role, sep = "_")) ## Convert user-friendly variable names to appropriate column names if (variable == "faculty") { variable <- "INS_Faculteit" variable_name <- "Faculteit" } else if (variable == "phase") { variable <- "INS_Opleidingsfase_BPM" variable_name <- "Fase" } else if (variable == "opleiding") { variable <- "INS_Opleidingsnaam_2002" variable_name <- "Opleiding" } else if (variable == "cohort") { variable <- "INS_Inschrijvingsjaar_EOI" variable_name <- "Cohort" } else { variable_name <- variable } label <- variable_name ## Create a named list with unique values as names choices <- sort(unique(df[[variable]])) %>% purrr::set_names(.) %>% purrr::map(~ paste(.x, variable, sep = ";")) if (length(selected) == 1 && selected == "All") { selected <- choices } ## Transform the string all to all choices shinyWidgets::pickerInput( inputId = inputId, label = label, choices = choices, selected = selected, multiple = multiple, options = list( `actions-box` = TRUE, `deselect-all-text` = "Geen", `select-all-text` = "Alles", `none-selected-text` = "-- GEEN FILTER --", `live-search` = TRUE ) ) } #' @title present_and_correct function #' @description Function to check if the column is present and correctly formed based on the element type. #' @param column_name A string representing the column name. #' @param element A string representing the element. Default is NA. #' @param df A data frame for which to check the column. Default is dfCombi_geaggregeerd. #' @return A boolean indicating whether the column is present and correctly formed. present_and_correct <- function(column_name, element = NA, df) { present <- column_name %in% names(df) ## Controleer per type grafiek-element of de kolom voldoet correct_form <- switch(element, ## # "x" = length(unique(df[[column_name]])) < 15, "x" = TRUE, "y" = typeof(df[[column_name]]) %in% c("logical", "double", "integer") & class(df[[column_name]]) != "Date", "y_links" = typeof(df[[column_name]]) %in% c("logical", "double", "integer") & class(df[[column_name]]) != "Date", "y_rechts" = typeof(df[[column_name]]) %in% c("logical", "double", "integer") & class(df[[column_name]]) != "Date", # "color" = TRUE "color" = is.logical(df[[column_name]]) | is.integer(df[[column_name]]) & length(unique(df[[column_name]])) < 15 | is.character(df[[column_name]]) & length(unique(df[[column_name]])) < 15, "sankey" = is.logical(df[[column_name]]) | is.integer(df[[column_name]]) & length(unique(df[[column_name]])) < 15 | is.character(df[[column_name]]) & length(unique(df[[column_name]])) < 15 ) ## Set correct form to TRUE when the element is not defined if (is.null(correct_form)) { correct_form <- TRUE } ## Combine the two checks result <- present & correct_form return(result) }
/scratch/gouwar.j/cran-all/cranData/vvshiny/R/ui_pickers_general.R
#' @title pickerSankeyVar function #' @description Function to pick variables for state in a Sankey diagram. #' @param id A string representing the id of the input element. #' @param df_sankey A data frame containing the Sankey diagram data. #' @param df_config_sankey A data frame containing the Sankey configuration. #' @param state A string representing the state of the variable. Default is "left_var". #' @return A pickerInput object. pickerSankeyVar <- function(id, df_sankey, df_config_sankey, state = "left_var") { Categorie <- group_split <- NULL id_state <- shiny::NS(id, state) if (state == "left_var") { text <- "links" } else if (state == "right_var") { text <- "rechts" } lVariables <- df_config_sankey %>% dplyr::filter(!is.na(!!rlang::sym(state))) %>% dplyr::mutate(Categorie = factor(Categorie)) %>% group_split(Categorie) %>% purrr::set_names(purrr::map_chr(., ~ .x$Categorie[1] %>% as.character())) %>% purrr::map(~ .x %>% dplyr::pull(target) %>% as.list()) %>% ## Iterate over elements purrr::map( ~ purrr::map( ## check if element is present and correctly formed .x, ~ purrr::keep(.x, present_and_correct(.x, df = df_sankey)) %>% ## set the display name per element purrr::set_names(display_name(.x, id)) ## Remove all empty elements ) %>% purrr::compact() %>% unlist() ) shinyWidgets::pickerInput( inputId = id_state, label = paste("variabele", text, sep = " "), choices = lVariables, selected = lVariables[[1]][[1]] ) } #' @title pickerSankeyValues function #' @description Function to pick values for transition of the two Sankey states. #' @param id A string representing the id of the input element. #' @param filter_var A string representing the variable to filter. #' @param df_sankey A data frame containing the Sankey diagram data. #' @param side A string representing the side of the Sankey diagram. #' @return A pickerInput object. pickerSankeyValues <- function(id, filter_var, df_sankey, side) { inputId_base <- paste0("filter_", side) inputId <- shiny::NS(id, inputId_base) values <- unique(df_sankey[[filter_var]]) shinyWidgets::pickerInput( inputId = inputId, label = paste0("filter ", side), choices = values, selected = values[1:5], multiple = TRUE ) } #' @title pickerGanttVar function #' @description Function to pick a variable to show values in a Gantt chart. #' @param id A string representing the id of the input element. #' @param element A string representing the element. #' @param df_config_gantt A data frame containing the Gantt configuration. #' @param input_var_value A variable value from the input. Default is NULL. pickerGanttVar <- function(id, element, df_config_gantt, input_var_value = NULL) { input_var <- target_var <- Categorie <- NULL id_element <- shiny::NS(id, element) if (element == "target_var") { basic_choices <- df_config_gantt %>% dplyr::filter(input_var == input_var_value) %>% dplyr::pull(target_var) %>% unique() label <- "doel variable" } else if (element == "input_var") { basic_choices <- df_config_gantt[[element]] %>% unique() label <- "input variabele" } ## Set friendly names for choices choices <- df_config_gantt %>% ## Keep only earlier selected choices dplyr::filter(!!rlang::sym(element) %in% basic_choices) %>% ## Split per category dplyr::mutate(Categorie = factor(Categorie)) %>% dplyr::group_split(Categorie) %>% purrr::set_names(purrr::map_chr(., ~ .x$Categorie[1] %>% as.character())) %>% purrr::map(~ .x %>% # dplyr::filter(!!rlang::sym(element) %in% choices) %>% dplyr::pull(!!rlang::sym(element)) %>% as.list() %>% unique()) %>% purrr::map( ~ purrr::set_names(.x, ~ purrr::map_chr(.x, ~ display_name(.x, id))) ) shinyWidgets::pickerInput( inputId = id_element, label = label, choices = choices, selected = choices[[1]][[1]] ) } #' @title pickerGanttValues function #' @description Function to filter the values in the Gantt chart. #' @param id A string representing the id of the input element. #' @param filter_var A string representing the variable to filter. #' @param df_doorstroom_gantt A data frame containing the Gantt chart data. #' @return A pickerInput object. pickerGanttValues <- function(id, filter_var, df_doorstroom_gantt) { inputId <- shiny::NS(id, "filter") shinyWidgets::pickerInput( inputId = inputId, label = "input filter", choices = unique(df_doorstroom_gantt[[filter_var]]) ) }
/scratch/gouwar.j/cran-all/cranData/vvshiny/R/ui_pickers_special.R
#' @title dropdownTabMenu function #' @description Dropdown that is actually more of a menu with adapted tasks. #' @param ... additional arguments. #' @param type A character vector of either "messages", "notifications", "tasks". Default is c("messages", "notifications", "tasks"). #' @param title The title of the dropdown. #' @param icon The icon to use in the dropdown. If NULL, defaults will be set based on type. #' @param .list A list of items to add to the dropdown. #' @param header The header for the dropdown. #' @return A dropdown menu in the form of an HTML list. #' @export #' @examples #' dropdownTabMenu(type = "messages", title = "Category tab items") dropdownTabMenu <- function(..., type = c("messages", "notifications", "tasks"), title = NULL, icon = NULL, .list = NULL, header = NULL) { type <- match.arg(type) if (is.null(icon)) { icon <- switch(type, messages = shiny::icon("envelope"), notifications = shiny::icon("warning"), tasks = shiny::icon("tasks") ) } items <- c(list(...), .list) dropdownClass <- paste0("dropdown ", type, "-menu") htmltools::tags$li(class = dropdownClass, htmltools::a( href = "#", class = "dropdown-toggle", `data-toggle` = "dropdown", icon, title ), htmltools::tags$ul( class = "dropdown-menu", if (!is.null(header)) htmltools::tags$li(class = "header", header), htmltools::tags$li(htmltools::tags$ul(class = "menu", items)) )) } #' @title dropdownTabDirect function #' @description Dropdown that is actually a link to a tab. #' @param type A character vector of either "messages", "notifications", "tasks". Default is c("messages", "notifications", "tasks"). #' @param tab_name The name of the tab to link to. #' @param title The title of the dropdown. #' @param icon The icon to use in the dropdown. If NULL, defaults will be set based on type. #' @param .list A list of items to add to the dropdown. #' @param header The header for the dropdown. #' @return A dropdown menu in the form of an HTML list, where clicking the dropdown directs to a specific tab. #' @export #' @examples #' dropdownTabDirect(type = "messages", tab_name = "Tab1", title = "Interesting tab") dropdownTabDirect <- function(type = c("messages", "notifications", "tasks"), tab_name, title, icon = NULL, .list = NULL, header = NULL) { type <- match.arg(type) if (is.null(icon)) { icon <- switch(type, messages = shiny::icon("envelope"), notifications = shiny::icon("warning"), tasks = shiny::icon("tasks") ) } tabSelect <- TRUE dropdownClass <- paste0("dropdown ", type, "-menu") htmltools::tags$li( class = dropdownClass, htmltools::a( href = "#", onclick = paste0("shinyjs.tabSelect('", tab_name, "')"), icon, title, `data-tab-name` = tab_name, class = "dropdown-toggle", `data-toggle` = "dropdown" ) ) } #' @title taskItemTab function #' @description Item for above dropdownActionMenu function. #' @param text The text to display for the item. #' @param tab_name The name of the tab to link to. Default is NULL. #' @param href The href link for the item. If NULL, it defaults to "#". #' @param tabSelect A boolean indicating whether to select the tab. Default is FALSE. #' @return An HTML list item. #' @export #' @examples #' taskItemTab(text = "Selected tab", tab_name = "Tab1", tabSelect = TRUE) #' taskItemTab(text = "Other tab", tab_name = "Tab2", tabSelect = FALSE) taskItemTab <- function(text, tab_name = NULL, href = NULL, tabSelect = FALSE) { if (is.null(href)) href <- "#" if (tabSelect) { htmltools::tags$li(htmltools::a(onclick = paste0("shinyjs.tabSelect('", tab_name, "')"), text, `data-tab-name` = tab_name)) } else { htmltools::tags$li(htmltools::a(href = href, htmltools::h3(text))) } }
/scratch/gouwar.j/cran-all/cranData/vvshiny/R/ui_shinydashboardplus_adaptions.R
## @title tabPanelTables function ## @description Function to define the structure of tables based on the 'id' parameter. ## @param id A string representing the id. ## @param table_one A string representing the first table. Default is "tabel". ## @param table_two A string representing the second table. Default is "tabel_twee". ## @return A tab panel with one or two tables based on the 'id' parameter. tabPanelTables <- function(id, table_one = "tabel", table_two = "tabel_twee") { if (stringr::str_detect(id, "bench")) { ## Call function to create a tab panel with two tables tabTableTwo(id, table_one, table_two) } else if (stringr::str_detect(id, "comp")) { ## Call function to create a tab panel with one table tabTableOne(id, table_one) } } #' @title tabTableOne function #' @description Function to create a tab panel with one table. #' @param id A string representing the id. #' @param table_one A string representing the table. #' @return A tab panel with one table. #' @export #' @examples #' dummy_data <- data.frame( #' A = 1:5, #' B = letters[1:5] #' ) #' dummy_dt <- DT::datatable(dummy_data) #' tabTableOne("dummy_id", dummy_dt) tabTableOne <- function(id, table_one) { shiny::tabPanel( "Tabel", shiny::fluidRow( shiny::column( width = 12, align = "center", shinycssloaders::withSpinner(DT::DTOutput(shiny::NS(id, table_one))) ) ) ) } #' @title tabTableTwo function #' @description Function to create a tab panel with two tables. #' @param id A string representing the id. #' @param table_one A string representing the first table. #' @param table_two A string representing the second table. #' @return A tab panel with two tables. #' @export #' @examples #' dummy_data1 <- data.frame( #' A = 1:5, #' B = letters[1:5] #' ) #' dummy_dt1 <- DT::datatable(dummy_data1) #' dummy_data2 <- data.frame( #' X = 6:10, #' Y = letters[6:10] #' ) #' dummy_dt2 <- DT::datatable(dummy_data2) #' tabTableTwo("dummy_id", dummy_dt1, dummy_dt2) tabTableTwo <- function(id, table_one, table_two) { shiny::tabPanel( "Tabel", shiny::fluidRow( shiny::column( width = 6, align = "center", shinycssloaders::withSpinner(DT::DTOutput(shiny::NS(id, table_one))) ), shiny::column( width = 6, align = "center", shinycssloaders::withSpinner(DT::DTOutput(shiny::NS(id, table_two))) ) ) ) } ## @title tabellenPopover function ## @description Function for creating popovers on the tabs of the tables. ## @param ... Arguments passed to other methods. ## @param tabblad A string representing the tab. ## @return A bsPopover from the spsComps package with specified content and style. tabellenPopover <- function(..., tabblad) { tabblad_info <- dplyr::case_when( tabblad == "Table" ~ "Text table", tabblad == "Composition percentages" ~ "Text composition %", TRUE ~ "Test" ) tabblad_tekst <- paste0("<br>", tabblad_info, "</br>") # Guard clause if (!requireNamespace("spsComps", quietly = TRUE)) { rlang::abort("The package spsComps should be installed for this funtion to work") } spsComps::bsPopover( tag = ..., title = tabblad, content = tabblad_tekst, placement = "left", bgcolor = "#3C8DBC", titlecolor = "white", contentcolor = "#3C8DBC", html = TRUE ) }
/scratch/gouwar.j/cran-all/cranData/vvshiny/R/ui_tab_tables.R
#' @keywords internal "_PACKAGE" ## usethis namespace: start ## usethis namespace: end NULL ## Syntatic sugar from tidyverse utils::globalVariables(c(":=", "!!", ".")) #' 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/vvshiny/R/vvshiny-package.R
## ---- include = FALSE--------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, eval = FALSE, comment = "#>" ) ## ----setup-------------------------------------------------------------------- # library(vvshiny)
/scratch/gouwar.j/cran-all/cranData/vvshiny/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 `vvshiny` package provides wrapper functions around ggplot / shiny / dplyr functions to make it easier to create a simple shiny app. ```{r setup} library(vvshiny) ```
/scratch/gouwar.j/cran-all/cranData/vvshiny/inst/doc/getting_started.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 `vvshiny` package provides wrapper functions around ggplot / shiny / dplyr functions to make it easier to create a simple shiny app. ```{r setup} library(vvshiny) ```
/scratch/gouwar.j/cran-all/cranData/vvshiny/vignettes/getting_started.Rmd
#' Add tags to a view in Tableau Server. #' #' Adds one or more tags to the specified view in the Tableau Server using the provided authentication credentials. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, `user_id`, and `site_id`. #' @param api_version The API version to use (default: 3.8). #' @param view_id The ID of the view to add tags to. #' @param tags A vector of tags to add to the view. #' #' @return The response from the API. #' @export #' #' @family Tableau REST API add_tags_to_view <- function(tableau, api_version = 3.8, view_id, tags) { base_url <- tableau$base_url token <- tableau$token site_id <- tableau$site_id url <- paste0( base_url, "api/", api_version, "/sites/", site_id, "/views/", view_id, "/tags" ) # Construct the request body request_body <- paste0( "<tsRequest>", "<tags>", paste0( "<tag label=\"", tags, "\" />", collapse = "" ), "</tags>", "</tsRequest>" ) api_response <- httr::PUT( url, httr::add_headers("X-Tableau-Auth" = token), body = request_body, encode = "xml" ) return(api_response) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/add_tags_to_view.R
#' Add tags to a workbook in Tableau Server. #' #' Adds one or more tags to the specified workbook in the Tableau Server using the provided authentication credentials. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, `user_id`, and `site_id`. #' @param api_version The API version to use (default: 3.8). #' @param workbook_id The ID of the workbook to add tags to. #' @param tags A vector of tags to add to the workbook. #' #' @return The response from the API. #' @export #' #' @family Tableau REST API add_tags_to_workbook <- function(tableau, api_version = 3.8, workbook_id, tags) { base_url <- tableau$base_url token <- tableau$token site_id <- tableau$site_id url <- paste0( base_url, "api/", api_version, "/sites/", site_id, "/workbooks/", workbook_id, "/tags" ) # Construct the request body request_body <- paste0( "<tsRequest>", "<tags>", paste0( "<tag label=\"", tags, "\" />", collapse = "" ), "</tags>", "</tsRequest>" ) api_response <- httr::PUT( url, httr::add_headers("X-Tableau-Auth" = token), body = request_body, encode = "xml" ) return(api_response) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/add_tags_to_workbook.R
#' Add User to Group #' #' Adds a user to the specified group. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, `user_id`, and `site_id`. #' @param api_version The version of the API to use, such as 3.19 (default: 3.19). #' @param group_id The ID of the group to add the user to. #' @param user_id The ID (not name) of the user to add. You can get the user ID by calling Get Users on Site. #' #' @return The response from the API. #' @export #' @family Tableau REST API add_user_to_group <- function(tableau, api_version = 3.19, group_id, user_id) { base_url <- tableau$base_url site_id <- tableau$site_id token <- tableau$token url <- paste0( base_url, "api/", api_version, "/sites/", site_id, "/groups/", group_id, "/users" ) request_body <- paste0( "<tsRequest>", "<user id=\"", user_id, "\" />", "</tsRequest>" ) api_response <- httr::POST( url, httr::add_headers("X-Tableau-Auth" = token), body = request_body ) return(api_response) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/add_user_to_group.R
#' Add User to Site #' #' Adds a user to Tableau Server or Tableau and assigns the user to the specified site. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, `user_id`, and `site_id`. #' @param site_role The site role to assign to the user. #' @param user_name The name of the user to add. #' @param auth_setting The authentication type for the user. #' @param api_version The API version to use (default: 3.19). #' #' @return The response from the API. #' @export #' #' @family Tableau REST API add_user_to_site <- function(tableau, site_role, user_name, auth_setting = NULL, api_version = 3.19) { base_url <- tableau$base_url token <- tableau$token site_id <- tableau$site_id url <- paste0( base_url, "api/", api_version, "/sites/", site_id, "/users" ) # Construct the request body request_body <- paste0( "<tsRequest>", "<user name=\"", user_name, "\"", " siteRole=\"", site_role, "\"", if (!is.null(auth_setting)) { paste0(" authSetting=\"", auth_setting, "\"") }, "/>", "</tsRequest>" ) # Check if the site role is valid valid_roles <- c("Creator", "Explorer", "ExplorerCanPublish", "SiteAdministratorExplorer", "SiteAdministratorCreator", "Unlicensed", "Viewer") if (!(site_role %in% valid_roles)) { stop("Invalid site role. Please choose one of the following: Creator, Explorer, ExplorerCanPublish, SiteAdministratorExplorer, SiteAdministratorCreator, Unlicensed, Viewer.") } api_response <- httr::POST( url, httr::add_headers("X-Tableau-Auth" = token), body = request_body ) return(api_response) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/add_user_to_site.R
#' adjust_tableau_font_style #' #' Adjust the font style of a tableau file #' #' @param import_files selected tableau file or folder, to change its font style. If #' it is only a file, make sure it is a twb file. #' @param font_style the name of the font style you want to use (in quotation marks "") #' @param save_location The location to which the adjusted tableau file will be #' saved (this needs to be a .twb file). If empty, the adjusted tableau file will be overwritten. #' #' @return tableau file with the correct font style. #' @export #' adjust_tableau_font_style <- function (import_files, font_style = "Tableau Regular", save_location = NULL) { # if the path gives a whole map instead of one file, make a file list. if (tools::file_ext(import_files) != "twb") { import_files = list.files(import_files, full.names = TRUE) } for (file in import_files) { #read xml file('s) data <- xml2::read_xml(file) # Find the font-style part style_part <- xml2::xml_find_all(data, "//formatted-text//run") for (type_section in style_part) { # change the style xml2::xml_set_attr(type_section, "fontname", font_style) } Ans_1 <- readline(prompt = "Do you want to save the adjustments in a new file? y/n: ") if (substr(Ans_1, 1, 1) == "y") { Ans_2 <- readline(prompt = "Yes, so did you give a new save file as input? y/n: ") if (substr(Ans_2, 1, 1) == "y") { cat("a new save file is given so this file will be used for saving \n") # check if the save_location file is .twb if (tools::file_ext(save_location) != "twb") { stop("save_location file is no .twb file") } # update and save the new file data <- XML::xmlParse(data) XML::saveXML(doc = data, file = save_location) } else { stop("stop the process, the user wants his file to be saved at onther file, however no new file as input is given.") } } else { cat("file can be overwritten \n") data <- XML::xmlParse(data) XML::saveXML(doc = data, file = file) } } }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/adjust_tableau_font_style.R
#' adjust_tableau_size #' #' Adjust the size of selected tableau file/files. #' #' @param import_files selected tableau file or folder, to change its size. If #' it is only one file, make sure it is a twb file. #' @param save_location The location to which the adjusted tableau file will be #' saved (this needs to be a .twb file). If empty, the adjusted tableau file will be overwritten. #' @param maxheight Max height for tableau file, if NULL use system variables. #' @param maxwidth Max width for tableau file, if NULL use system variables. #' @param minheight Min height for tableau file, if NULL use system variables. #' @param minwidth Min width for tableau file, if NULL use system variables. #' #' @return tableau file with the correct size. #' @export #' @family xml adjust_tableau_size <- function(import_files, save_location = NULL, maxheight = NULL, maxwidth = NULL, minheight = NULL, minwidth = NULL) { if (tools::file_ext(import_files) != "twb") { import_files = list.files(import_files, full.names = TRUE) } for (file in import_files) { data <- xml2::read_xml(file) # Find the size part style_part <- xml2::xml_find_all(data, "//style ") size_part <- xml2::xml_find_all(style_part, "//size[@minwidth]") ## adjust the size part if (is.null(c(maxheight, maxwidth, minheight, minwidth))) { minheight <- maxheight <- Sys.getenv("TABLEAU_HEIGHT") minwidth <- maxwidth <- Sys.getenv("TABLEAU_WIDTH") } xml2::xml_set_attrs(size_part, c("maxheight" = maxheight, "maxwidth" = maxwidth, "minheight" = minheight, "minwidth" = minwidth)) ## save adjusments Ans_1 <- readline(prompt = "Do you want to save the adjustments in a new file? y/n: ") if (substr(Ans_1, 1, 1) == "y") { Ans_2 <- readline(prompt = "Yes, so did you give a new save file as input? y/n: ") if (substr(Ans_2, 1, 1) == "y") { cat("a new save file is given so this file will be used for saving \n") # check if the save_location file is .twb if (tools::file_ext(save_location) != "twb") { stop("save_location file is no .twb file") } # update and save the new file data <- XML::xmlParse(data) XML::saveXML(doc = data, file = save_location) } else { stop( "stop the process, the user wants his file to be saved at onther file, however no new file as input is given." ) } } else { cat("file can be overwritten \n") data <- XML::xmlParse(data) XML::saveXML(doc = data, file = file) } } }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/adjust_tableau_size.R
#' Authenticate to Tableau Server or Tableau Cloud #' #' This function authenticates to a Tableau Server or Tableau Cloud using a personal access token (PAT). #' #' @param pat_name The name of the personal access token (PAT). Defaults to the `TABLEAU_PAT_NAME` environment variable. #' @param pat_secret The secret of the personal access token (PAT). Defaults to the `TABLEAU_PAT_SECRET` environment variable. #' @param content_url The URL of the content to authenticate. Defaults to the `TABLEAU_CONTENT_URL` environment variable. #' For Tableau Server, this is typically the URL of the Tableau server followed by the site ID. For Tableau Cloud, this is usually the URL of the Tableau cloud workbook. #' @param base_url The base URL of the Tableau server or Tableau cloud. Defaults to the `TABLEAU_BASE_URL` environment variable. #' For Tableau Server, this is usually the URL of the Tableau server. For Tableau Cloud, this is usually the URL of the Tableau cloud, #' and it must contain the pod name, such as 10az, 10ay, or us-east-1. #' For example, the base URL to sign in to a site in the 10ay pod would be: https://10ay.online.tableau.com. #' @param api_version The API version to use. Default is 3.4. #' @return A list containing the base URL, the access token, the site ID, and the user ID. #' @export #' @family Tableau REST API authenticate_PAT <- function(pat_name = tableau_pat_name(), pat_secret = tableau_pat_secret(), content_url = tableau_content_url(), base_url = tableau_base_url(), api_version = 3.4) { constructXML <- function(pat_name, pat_secret, content_url) { credentials <- paste0( "<credentials personalAccessTokenName=\"", pat_name, "\" personalAccessTokenSecret=\"", pat_secret, "\">") site <- paste0( "<site contentUrl=\"", content_url, "\"/>") tsRequest <- paste0( "<tsRequest>", credentials, site, "</credentials>", "</tsRequest>") return(tsRequest) } xml_request <- constructXML(pat_name, pat_secret, content_url) url <- paste0(base_url, "/api/", api_version, "/auth/signin") api_response <- httr::POST(url, body = xml_request, httr::verbose(), httr::content_type("application/xml"), httr::add_headers(`Accept` = "application/json"), httr::accept_json()) # Check the response status code if (httr::status_code(api_response) != 200) { stop("Authentication failed. Please check your API key and base URL.") } jsonResponseText <- httr::content(api_response, as = "text") dfauth <- as.data.frame(jsonlite::fromJSON(jsonResponseText), check.names = FALSE) %>% dplyr::rename_with(~ stringr::str_remove(., "credentials."), dplyr::everything()) tableau <- list( base_url = base_url, token = dfauth$token, site_id = dfauth$site.id, user_id = dfauth$id ) return(tableau) } #' Get the Tableau PAT name from the environment variable #' #' @return The Tableau PAT name stored in the TABLEAU_PAT_NAME environment variable. tableau_pat_name <- function() { pat_name <- Sys.getenv("TABLEAU_PAT_NAME") if (pat_name == "") { stop("TABLEAU_PAT_NAME environment variable is not set.") } return(pat_name) } #' Get the Tableau PAT secret from the environment variable #' #' @return The Tableau PAT secret stored in the TABLEAU_PAT_SECRET environment variable. tableau_pat_secret <- function() { pat_secret <- Sys.getenv("TABLEAU_PAT_SECRET") if (pat_secret == "") { stop("TABLEAU_PAT_SECRET environment variable is not set.") } return(pat_secret) } #' Get the Tableau content URL from the environment variable #' #' @return The Tableau content URL stored in the TABLEAU_CONTENT_URL environment variable. tableau_content_url <- function() { content_url <- Sys.getenv("TABLEAU_CONTENT_URL") if (content_url == "") { stop("TABLEAU_CONTENT_URL environment variable is not set.") } return(content_url) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/authenticate_PAT.R
#' Authenticate on the Tableau server. #' #' Authenticates the user on the Tableau server and retrieves the necessary authentication variables for running other Tableau REST API methods. #' #' @param username The username on the Tableau server. Defaults to the `TABLEAU_USERNAME` environment variable. #' @param password The password on the Tableau server. Defaults to the `TABLEAU_PASSWORD` environment variable. #' @param base_url The base URL of the Tableau server. Defaults to the `TABLEAU_BASE_URL` environment variable. #' @param api_version The API version to use (default: 3.4). #' #' @return A list containing the authentication variables: base_url, token, site_id, and user_id. #' @export #' #' @family Tableau REST API authenticate_server <- function(username = tableau_username(), password = tableau_password(), base_url = tableau_base_url(), api_version = 3.4) { tableau <- list(base_url = base_url) # Check if the base URL ends with a trailing slash and remove it if present if (substr(tableau$base_url, nchar(tableau$base_url), nchar(tableau$base_url)) == "/") { tableau$base_url <- substr(tableau$base_url, 1, nchar(tableau$base_url) - 1) } credentials <- paste0( '<credentials name="', username, '" password="', password, '">' ) xml_request <- paste("<tsRequest>", credentials, '<site contentUrl="" />', "</credentials>", "</tsRequest>", collapse = "\n" ) url <- paste0( base_url, "api/", api_version, "/auth/signin" ) api_response <- httr::POST(url, body = xml_request, httr::verbose(), httr::content_type("text/xml") ) # Check the response status code if (httr::status_code(api_response) != 200) { stop("Authentication failed. Please check your API key and base URL.") } jsonResponseText <- httr::content(api_response, as = "text") dfauth <- as.data.frame(jsonlite::fromJSON(jsonResponseText), check.names = FALSE) %>% dplyr::rename_with(~ stringr::str_remove(., "credentials."), dplyr::everything()) tableau <- list( base_url = base_url, token = dfauth$token, site_id = dfauth$site.id, user_id = dfauth$id ) return(tableau) } #' Get the Tableau username from the environment variable #' #' @return The Tableau username stored in the TABLEAU_USERNAME environment variable. tableau_username <- function() { username <- Sys.getenv("TABLEAU_USERNAME") if (username == "") { stop("TABLEAU_USERNAME environment variable is not set.") } return(username) } #' Get the Tableau password from the environment variable #' #' @return The Tableau password stored in the TABLEAU_PASSWORD environment variable. tableau_password <- function() { password <- Sys.getenv("TABLEAU_PASSWORD") if (password == "") { stop("TABLEAU_PASSWORD environment variable is not set.") } return(password) } #' Get the Tableau base URL from the environment variable #' #' @return The Tableau base URL stored in the TABLEAU_BASE_URL environment variable. tableau_base_url <- function() { base_url <- Sys.getenv("TABLEAU_BASE_URL") if (base_url == "") { stop("TABLEAU_BASE_URL environment variable is not set.") } return(base_url) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/authenticate_server.R
#' check_dashboard_names #' #' Check the names of dashboards in tableau, according to the style guide. #' The wrong dashboards will be returned together with the reason why it is a #' wrong name #' #' @param import_files selected tableau file or folder, #' to check the names of the dashboards. #' If it is only one file, make sure it is a twb file. #' #' @return the wrongly named dashboards #' @export #' @family xml check_dashboard_names <- function(import_files) { if (tools::file_ext(import_files) != "twb") { import_files = list.files(import_files, full.names = TRUE) } for (file in import_files) { data <- XML::xmlParse(file = file) ## Extract de root node. rootnode <- XML::xmlRoot(data) ## Find the dashboards part DB_part <- rootnode[["dashboards"]] ## Find the amount of dashboards number_of_DB <- length(XML::xmlChildren(DB_part)) ## while loop over all DB's to save each dashboards current name count <- 1 name_list <- list() while (count <= number_of_DB) { DB_names <- rootnode[["dashboards"]][[count]] name_list <- append(name_list, XML::xmlAttrs(DB_names)) count <- count + 1 } ## check all conditions for a correct DB name names <- 1 while (names <= number_of_DB) { if (name_list[names] == "Filters" || name_list[names] == "Toelichting") { ## do nothing, it is a correct name, so skip it. } else if (name_list[names] == "filters" || name_list[names] == "toelichting") { print(paste0("Wrong DB name: '", name_list[names], "', not starting with an capital letter")) } else if (stringr::str_detect(name_list[names], "^\\d.") == F) { print(paste0("Wrong DB name: '", name_list[names],"', not starting with a digit and a dot")) } else if (stringr::str_detect(name_list[names], "[A-Z]") == F) { print(paste0("Wrong DB name: '", name_list[names], "', not starting with an capital letter")) } else if (grepl("DB", name_list[names]) == T) { print(paste0("Wrong DB name: '", name_list[names], "', no 'DB' allowed in DB name")) } names <- names + 1 } } }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/check_dashboard_names.R
#' Create Group #' #' Creates a group on Tableau Server or Tableau Cloud site. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, and `site_id`. #' @param group_name The name of the group to create. #' @param api_version The API version to use (default: 3.19). #' #' @return The ID of the new group. #' @export #' #' @family Tableau REST API create_group <- function(tableau, group_name, api_version = 3.19) { base_url <- tableau$base_url token <- tableau$token site_id <- tableau$site_id url <- paste0( base_url, "/api/", 3.19, "/sites/", site_id, "/groups" ) # Construct the request body request_body <- paste0( "<tsRequest>", "<group name=\"", group_name, "\"/>", "</tsRequest>" ) api_response <- httr::POST( url, httr::add_headers("X-Tableau-Auth" = token), body = request_body ) # Check the response status code if (httr::status_code(api_response) != 201) { stop("Group creation failed. Please check your API key and base URL.") } # Extract the ID of the new group from the Location header location_header <- httr::headers(api_response)$location group_id <- stringr::str_extract(location_header, "\\w{8}-\\w{4}-\\w{4}-\\w{4}-\\w{12}") return(group_id) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/create_group.R
#' Delete Group #' #' Deletes the specified group from the site. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, `user_id`, and `site_id`. #' @param group_id The ID of the group to delete. #' @param api_version The API version to use (default: 3.19). #' @export #' @family Tableau REST API delete_group <- function(tableau, group_id, api_version = 3.19) { base_url <- tableau$base_url site_id <- tableau$site_id token <- tableau$token url <- paste0( base_url, "api/", api_version, "/sites/", site_id, "/groups/", group_id ) api_response <- httr::DELETE(url, httr::add_headers("X-Tableau-Auth" = token) ) # Check the response status code if (httr::status_code(api_response) != 204) { stop("Group deletion failed. Please check your API key and base URL.") } }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/delete_group.R
#' Download a data source in .tdsx format using Tableau REST API and save it as a file. #' #' Downloads a data source in .tdsx format and saves it as a file on your computer. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, `user_id`, and `site_id`. #' @param api_version The API version to use (default: 3.16). #' @param datasource_id The ID of the data source to download. #' @param file_path The path to save the downloaded data source. #' @param include_extract Logical indicating whether to include the extract when downloading the data source (default: TRUE). #' @return A binary vector containing the data source in .tdsx format. #' @export #' @family Tableau REST API download_datasource <- function(tableau, api_version = 3.16, datasource_id, file_path, include_extract = TRUE) { base_url <- tableau$base_url token <- tableau$token site_id <- tableau$site_id url <- paste0( base_url, "api/", api_version, "/sites/", site_id, "/datasources/", datasource_id, "/content" ) if (!include_extract) { url <- paste0(url, "?includeExtract=False") } api_response <- httr::GET( url, httr::add_headers("X-Tableau-Auth" = token), httr::write_disk(paste0(file_path, "data.tdsx"), overwrite = TRUE) ) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/download_datasource.R
#' Download Tableau view crosstab as Excel #' #' Downloads the crosstab data from a Tableau view in Excel format. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, `user_id`, and `site_id`. #' @param view_id The ID of the view to download. #' @param path_to_save The directory to write the crosstab Excel file to. #' @param api_version The API version to use (default: 3.16). #' #' @return NULL #' @family Tableau REST API #' #' @export download_tableau_crosstab_excel <- function(tableau, view_id, path_to_save, api_version = 3.16) { base_url <- tableau$base_url token <- tableau$token site_id <- tableau$site_id # Define the base URL base_url <- paste0(base_url, "api/", api_version, "/sites/", site_id, "/views/", view_id, "/crosstab/excel") # Download the crosstab as Excel httr::GET( base_url, httr::add_headers("X-Tableau-Auth" = token), httr::write_disk(paste0(path_to_save, "crosstab.xlsx"), overwrite = TRUE) ) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/download_tableau_crosstab_excel.R
#' Download Tableau view data as Excel #' #' Downloads the data from a Tableau view in Excel format. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, `user_id`, and `site_id`. #' @param view_id The ID of the view to download. #' @param path_to_save The directory to write the data Excel file to. #' @param api_version The API version to use (default: 3.8). #' #' @return NULL #' #' @export #' #' @family Tableau REST API download_tableau_data <- function(tableau, view_id, path_to_save, api_version = 3.8) { base_url <- tableau$base_url token <- tableau$token site_id <- tableau$site_id # Define the base URL base_url <- paste0( base_url, "api/", api_version, "/sites/", site_id, "/views/", view_id, "/data" ) # Construct the URL url <- paste0(base_url, "?format=csv") # Download the data as CSV httr::GET( url, httr::add_headers(`X-Tableau-Auth` = token), httr::write_disk(paste0(path_to_save, "data.csv"), overwrite = TRUE) ) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/download_tableau_data.R
#' Download filtered Tableau views to PNG images from a dataframe. #' #' Downloads PNG images of filtered Tableau views based on the provided dataframe containing filter columns and filter values. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, `user_id`, and `site_id`. #' @param df Dataframe containing filter columns and filter values. #' @param view_id The ID of the view to download. #' @param path_to_save The directory to write the images to. #' @param api_version The API version to use (default: 3.8). #' #' @export #' #' @family Tableau REST API download_filtered_tableau_image <- function(tableau, df, view_id, path_to_save, api_version = 3.8) { base_url <- tableau$base_url token <- tableau$token site_id <- tableau$site_id # Define the base URL base_url <- paste0( base_url, "api/", api_version, "/sites/", site_id, "/views/", view_id, "/image" ) # Iterate over rows of the dataframe purrr::pmap(df, function(...) { name <- row_to_name(c(...)) query <- row_to_query(c(...)) url <- paste0(base_url, query, "&resolution=high") # Download the image httr::GET( url, httr::add_headers(`X-Tableau-Auth` = token), httr::write_disk(paste0(path_to_save, name, ".png"), overwrite = TRUE) ) }) } #' Escape characters for url #' #' @param url the url #' #' @return escaped string escape_special_chars <- function(url) { url <- gsub(" ", "%20", url) url <- gsub(",", "%5C%2C", url) url <- gsub("&", "%26", url) url <- gsub("\\^", "%5E", url) return(url) } #' Dataframe row to query #' #' @param row row of dataframe #' #' @return Query to the api call row_to_query <- function(row) { # Use paste to concatenate "vf_", column names, "=", and row values filter_strs <- paste0("vf_", names(row), "=", escape_special_chars(row)) # Combine the filter strings with "&" and prepend "?" query <- paste0("?", paste(filter_strs, collapse = "&")) return(query) } #' Concat row to name #' #' @param row row of dataframe #' #' @return namr of the row row_to_name <- function(row) { # Use paste to concatenate "vf_", column names, "=", and row values filter_strs <- paste0(as.character(row), collapse = "") # Combine the filter strings with "&" and prepend "?" query <- paste0((filter_strs)) return(query) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/download_view_filtered.R
#' Download workbook from Tableau Server. #' #' Downloads a workbook from the Tableau Server using the provided authentication credentials and saves it to the specified path. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, `user_id`, and `site_id`. #' @param api_version The API version to use (default: 3.4). #' @param workbook_id The identifier of the workbook to download. #' @param path_to_save The file path to save the downloaded workbook. #' @param include_extract Logical indicating whether to include the extract file (default: FALSE). #' #' @return NULL. #' @export #' #' @family Tableau REST API download_workbooks_server <- function(tableau, api_version = 3.4, workbook_id, path_to_save, include_extract = FALSE) { base_url <- tableau$base_url token <- tableau$token site_id <- tableau$site_id url <- paste0( base_url, "api/", api_version, "/sites/", site_id, "/workbooks/", workbook_id, "/content?includeExtract=", include_extract ) api_response <- httr::GET( url, httr::add_headers("X-Tableau-Auth" = token), httr::write_disk(path_to_save) ) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/download_workbook_server.R
#' Download workbook PDF from Tableau Server. #' #' Downloads a PDF version of a workbook from the Tableau Server using the provided authentication credentials and saves it to the specified path. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, `user_id`, and `site_id`. #' @param api_version The API version to use (default: 3.4). #' @param workbook_id The identifier of the workbook to download. #' @param path_to_save The file path to save the downloaded PDF file. #' #' @return NULL. #' @export #' #' @family Tableau REST API download_workbooks_server_pdf <- function(tableau, api_version = 3.4, workbook_id, path_to_save) { base_url <- tableau$base_url token <- tableau$token site_id <- tableau$site_id url <- paste0( base_url, "api/", api_version, "/sites/", site_id, "/workbooks/", workbook_id, "/pdf" ) api_response <- httr::GET( url, httr::add_headers("X-Tableau-Auth" = token), httr::write_disk(path_to_save) ) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/download_workbook_server_pdf.R
#' Download workbook PowerPoint from Tableau Server. #' #' Downloads a PowerPoint version of a workbook from the Tableau Server using the provided authentication credentials and saves it to the specified path. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, `user_id`, and `site_id`. #' @param api_version The API version to use (default: 3.8). #' @param workbook_id The identifier of the workbook to download. #' @param path_to_save The file path to save the downloaded PowerPoint file. #' #' @return NULL. #' @export #' #' @family Tableau REST API download_workbooks_server_powerpoint <- function(tableau, api_version = 3.8, workbook_id, path_to_save) { base_url <- tableau$base_url token <- tableau$token site_id <- tableau$site_id url <- paste0( base_url, "api/", api_version, "/sites/", site_id, "/workbooks/", workbook_id, "/powerpoint" ) api_response <- httr::GET( url, httr::add_headers("X-Tableau-Auth" = token), httr::write_disk(path_to_save) ) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/download_workbook_server_powerpoint.R
#' Get Workbook actions #' #' @param wb The path to the Tableau workbook [.twb]. #' #' @return Dataframe containing the workbook actions. #' @export #' #' @family xml #' @examples #' \dontrun{ #' # Get Workbook actions #' actions <- get_actions(wb = "path/to/workbook.twb") #' head(actions) #' } get_actions <- function(wb) { proc <- make_rootnodes(wb) nodenames <- get_nodenames(proc) xy <- which(nodenames == "actions") if (!length(xy)) { stop("The workbook does not contain any actions.") } cc <- XML::getNodeSet(proc[[xy]], ".//action") z <- data.table::rbindlist(lapply(cc, function(x) { y <- t(XML::xpathSApply(x, ".", XML::xmlAttrs)) r <- t(XML::xpathSApply(x, ".//activation", XML::xmlAttrs)) s <- t(XML::xpathSApply(x, ".//source", XML::xmlAttrs)) t <- t(XML::xpathSApply(x, ".//target", XML::xmlAttrs)) data.frame(y, r, s, t) }), fill = TRUE) return(z) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/get_actions.R
#' Get folder structure workbook #' #' @param wb The path to the Tableau workbook file [.twb]. #' #' @return A dataframe containing the folder names and the variables stored inside. #' @export #' #' @family xml get_folders <- function(wb) { proc <- make_rootnodes(wb) nodenames <- get_nodenames(proc) xy <- which(nodenames == "datasources") cc <- XML::getNodeSet(proc[[xy]], ".//folder") if (!length(cc)) { stop("The workbook does not contain any folders.") } df <- data.table::rbindlist(lapply(cc, function(x) { r <- t(XML::xpathSApply(x, ".", XML::xmlAttrs)) var <- XML::xpathSApply(x, ".//folder-item", XML::xmlGetAttr, "name") data.frame(r, var) }), fill = TRUE) return(df) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/get_folders.R
#' Get Groups for a User #' #' Gets a list of groups that the specified user is a member of. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, `user_id`, and `site_id`. #' @param api_version The API version to use (default: 3.19). #' @param user_id The ID of the user whose group memberships are listed. #' @param page_size #' (Optional) The number of items to return in one response. The minimum is 1. The maximum is 1000. The default is 100. For more information, see Paginating Results. #' @param page_number #' (Optional) The offset for paging. The default is 1. For more information, see Paginating Results. #' @param include_metadata Logical indicating whether to include metadata columns in the result (default: FALSE). #' #' @return A table containing the groups for the specified user. #' @export #' @family Tableau REST API get_groups_for_user <- function(tableau, api_version = 3.19, user_id, page_size = 100, page_number = 1, include_metadata = FALSE) { base_url <- tableau$base_url site_id <- tableau$site_id token <- tableau$token url <- paste0( base_url, "api/", api_version, "/sites/", site_id, "/users/", user_id, "/groups" ) api_response <- httr::GET(url, httr::add_headers("X-Tableau-Auth" = token), httr::content_type("application/xml"), httr::accept_json()) if (httr::status_code(api_response) != 200) { stop("API call failed.") } jsonResponseText <- httr::content(api_response, as = "text") df <- jsonlite::fromJSON(jsonResponseText) %>% as.data.frame(check.names = FALSE) %>% dplyr::rename_with(~ stringr::str_remove(., "groups.group."), dplyr::everything()) if (!include_metadata) { df <- df %>% dplyr::select(-dplyr::starts_with("pagination")) } return(df) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/get_groups_for_user.R
#' Get Workbook drilldown hierarchies #' #' @param wb The path to the Tableau workbook [.twb]. #' #' @return Dataframe containing the workbook hierarchy drill downs. #' @export #' #' @family xml get_hierarchy <- function(wb) { proc <- make_rootnodes(wb) nodenames <- get_nodenames(proc) xy <- which(nodenames == "datasources") cc <- XML::getNodeSet(proc[[xy]], ".//drill-paths") if (!length(xy)) { stop("The workbook does not contain any hierarchy drilldowns") } df <- data.table::rbindlist(lapply(cc, function(x) { r <- t(XML::xpathSApply(x, ".//drill-path", XML::xmlAttrs)) var <- t(XML::xpathSApply(x, ".//drill-path", XML::getChildrenStrings)) data.frame(r, var) }), fill = TRUE) return(df) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/get_hierarchy.R
#' Get mobile security settings for the server using Tableau REST API. #' #' Retrieves the mobile security settings for the Tableau Server. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, `user_id`. #' @param api_version The API version to use (default: 3.19). #' @return A list containing the mobile security settings for the server. #' @export #' @family Tableau REST API get_mobile_security_settings <- function(tableau, api_version = 3.19) { base_url <- tableau$base_url token <- tableau$token url <- paste0( base_url, "api/", api_version, "/settings/mobilesecuritysettings" ) api_response <- httr::GET( url, httr::add_headers("X-Tableau-Auth" = token) ) jsonResponseText <- httr::content(api_response, as = "text") settings <- jsonlite::fromJSON(jsonResponseText) return(settings) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/get_mobile_security_settings.R
#' Get all nodenames #' #' @param proc The rootnode #' #' @return nodenames #' @export #' #' @family xml get_nodenames <- function(proc) { nodenames <- vapply(seq_along(XML::xmlChildren(proc)), function(x) { XML::xmlName(proc[[x]]) }, character(1)) return(nodenames) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/get_nodenames.R
#' Get all parameters in workbook. #' #' @param wb The path to the tableau workbook [.twb]. #' #' @return Dataframe #' @export #' #' @family xml get_parameter <- function(wb) { proc <- make_rootnodes(wb) nodenames <- get_nodenames(proc) xy <- which(nodenames == "datasources") cc <- XML::getNodeSet(proc[[xy]][[1]], ".//column") df <- data.table::rbindlist(lapply(cc, function(xz) { ab <- t(XML::xpathSApply(xz, paste0("."), XML::xmlAttrs)) ad <- t(XML::xpathSApply(xz, paste0(".//range"), XML::xmlAttrs)) ae <- t(XML::xpathSApply(xz, paste0(".//members//member"), XML::xmlAttrs)) data.frame(ab, ad, ae) }), fill = TRUE) return(df) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/get_parameters.R
#' Get the revision number #' #' @param wb The path to the Tableau workbook file [.twb]. #' #' @return The revision number #' @export #' #' @family xml get_revision <- function(wb) { proc <- make_rootnodes(wb) nodenames <- get_nodenames(proc) xy <- which(nodenames == "repository-location") Revision <- cbind(XML::xpathSApply(proc[[xy]], ".", XML::xmlGetAttr, "revision")) return(as.double(Revision)) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/get_revision.R
#' Get connected applications from Tableau Server. #' #' Retrieves information about connected applications from the Tableau Server using the provided authentication credentials. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, `user_id`, and `site_id`. #' @param api_version The API version to use (default: 3.14). #' @param page_size The number of records to retrieve per page (default: 100). #' #' @return A data frame containing the connected applications information. #' @export #' #' @family Tableau REST API get_server_connected_apps <- function(tableau, api_version = 3.14, page_size = 100) { base_url <- tableau$base_url token <- tableau$token site_id <- tableau$site_id url <- paste0( base_url, "api/", api_version, "/sites/", site_id, "/connected-applications" ) api_response <- httr::GET( url, httr::add_headers("X-Tableau-Auth" = token) ) jsonResponseText <- httr::content(api_response, as = "text") df <- as.data.frame(jsonlite::fromJSON(jsonResponseText), check.names = FALSE) return(df) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/get_server_connected_applications.R
#' Get datasources from Tableau Server. #' #' Retrieves information about datasources from the Tableau Server using the provided authentication credentials. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, `user_id`, and `site_id`. #' @param api_version The API version to use (default: 3.4). #' @param page_number The page number of the results to retrieve (default: 1). #' @param page_size The number of records to retrieve per page (default: 100). #' @param include_metadata Logical indicating whether to include metadata columns in the result (default: FALSE). #' #' @return A data frame containing the datasource information. #' @export #' #' @family Tableau REST API get_server_datasources <- function(tableau, api_version = 3.4, page_number = 1, page_size = 100, include_metadata = FALSE) { base_url <- tableau$base_url token <- tableau$token site_id <- tableau$site_id url <- paste0( base_url, "api/", api_version, "/sites/", site_id, "/datasources?fields=_all_&pageSize=", page_size, "&pageNumber=", page_number ) api_response <- httr::GET( url, httr::add_headers("X-Tableau-Auth" = token) ) jsonResponseText <- httr::content(api_response, as = "text") df <- as.data.frame(jsonlite::fromJSON(jsonResponseText), check.names = FALSE) %>% tidyr::unnest(names_sep = ".") %>% dplyr::rename_with(~ stringr::str_remove(., "datasources.datasource."), dplyr::everything()) if (!include_metadata) { df <- df %>% dplyr::select(-dplyr::starts_with("pagination")) } return(df) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/get_server_datasources.R
#' Get groups from Tableau Server. #' #' Retrieves a list of groups from the Tableau Server using the provided authentication credentials. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, `user_id`, and `site_id`. #' @param api_version The API version to use (default: 3.4). #' @param page_number The page number of the results to retrieve (default: 1). #' @param page_size The number of records to retrieve per page (default: 100). #' @param include_metadata Logical indicating whether to include metadata columns in the result (default: FALSE). #' #' @return A data frame containing the groups information. #' @export #' #' @family Tableau REST API get_server_groups <- function(tableau, api_version = 3.4, page_number = 1, page_size = 100, include_metadata = FALSE) { base_url <- tableau$base_url token <- tableau$token site_id <- tableau$site_id url <- paste0( base_url, "api/", api_version, "/sites/", site_id, "/groups?fields=_all_&pageSize=", page_size, "&pageNumber=", page_number ) api_response <- httr::GET( url, httr::add_headers("X-Tableau-Auth" = token) ) jsonResponseText <- httr::content(api_response, as = "text") df <- as.data.frame(jsonlite::fromJSON(jsonResponseText), check.names = FALSE) %>% dplyr::rename_with(~ stringr::str_remove(., "groups.group."), dplyr::everything()) if (!include_metadata) { df <- df %>% dplyr::select(-dplyr::starts_with("pagination")) } return(df) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/get_server_groups.R
#' Get datasources from Tableau Server. #' #' Retrieves information about the Tableau server site using the provided authentication credentials. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, `user_id`, and `site_id`. #' @param api_version The API version to use (default: 3.4). #' @param page_size The number of records to retrieve per page (default: 100). #' @param include_metadata Logical indicating whether to include metadata columns in the result (default: FALSE). #' #' @return A data frame containing the server site information. #' @export #' #' @family Tableau REST API get_server_info <- function(tableau, api_version = 3.4, page_size = 100, include_metadata = FALSE) { base_url <- tableau$base_url token <- tableau$token site_id <- tableau$site_id url <- paste0( base_url, "api/", api_version, "/sites/", site_id, "/?includeUsage=true" ) api_response <- httr::GET( url, httr::add_headers("X-Tableau-Auth" = token) ) jsonResponseText <- httr::content(api_response, as = "text") df <- as.data.frame(jsonlite::fromJSON(jsonResponseText), check.names = FALSE) if (!include_metadata) { df <- df %>% dplyr::select(-dplyr::starts_with("pagination")) } return(df) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/get_server_info.R
#' Get server jobs from Tableau server. #' #' Retrieves a list of server jobs from the Tableau server using the provided authentication credentials. #' #' @param tableau A list containing the Tableau authentication variables: base_url, token, user_id, and site_id. #' @param api_version The API version to use (default: "3.4"). #' @param page_number The page number of the results to retrieve (default: 1). #' @param page_size The number of jobs to retrieve per page (default: 100). #' @param include_metadata Logical indicating whether to include metadata columns in the result (default: FALSE). #' #' @return A data frame containing the server jobs information. #' @export #' #' @family Tableau REST API get_server_jobs <- function(tableau, api_version = 3.4, page_number = 1, page_size = 100, include_metadata = FALSE) { base_url <- tableau$base_url token <- tableau$token user_id <- tableau$user_id site_id <- tableau$site_id url <- paste0( base_url, "api/", api_version, "/sites/", site_id, "/jobs?fields=_all_&pageSize=", page_size, "&pageNumber=", page_number ) api_response <- httr::GET( url, httr::add_headers("X-Tableau-Auth" = token) ) jsonResponseText <- httr::content(api_response, as = "text") df <- jsonlite::fromJSON(jsonResponseText) %>% as.data.frame() %>% dplyr::rename_all(~ stringr::str_remove(., "backgroundJobs.backgroundJob.")) if (!include_metadata) { df <- df %>% dplyr::select(-dplyr::starts_with("pagination")) } return(df) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/get_server_jobs.R
#' Get the server location. #' #' @param wb The path to the Tableau workbook [.twb]. #' #' @return The server location of the workbook. #' @export #' #' @family xml get_server_location <- function(wb) { proc <- make_rootnodes(wb) nodenames <- get_nodenames(proc) xy <- which(nodenames == "repository-location") if (!length(xy)) { stop("The workbook is not hosted on the Tableau server") } server_location <- cbind(XML::xpathSApply(proc[[xy]], ".", XML::xmlGetAttr, "derived-from")) return(as.character(server_location)) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/get_server_location.R
#' Get projects from Tableau server. #' #' Retrieves a list of projects from the Tableau server using the provided authentication credentials. #' #' @param tableau A list containing the Tableau authentication variables: base_url, token, site_id, and user_id. #' @param api_version The API version to use (default: "3.4"). #' @param page_number The page number of the results to retrieve (default: 1). #' @param page_size The number of projects to retrieve per page (default: 100). #' @param include_metadata Logical indicating whether to include metadata columns in the result (default: FALSE). #' #' @return A data frame containing the projects information. #' @export #' #' @family Tableau REST API get_server_projects <- function(tableau, api_version = 3.4, page_number = 1, page_size = 100, include_metadata = FALSE) { base_url <- tableau$base_url token <- tableau$token user_id <- tableau$user_id site_id <- tableau$site_id url <- paste0( base_url, "api/", api_version, "/sites/", site_id, "/projects?fields=_all_&pageSize=", page_size, "&pageNumber=", page_number ) api_response <- httr::GET( url, httr::add_headers("X-Tableau-Auth" = token) ) jsonResponseText <- httr::content(api_response, as = "text") df <- jsonlite::fromJSON(jsonResponseText) %>% as.data.frame(check.names = FALSE) %>% dplyr::rename_all(~ stringr::str_remove(., "projects.project.")) if (!include_metadata) { df <- df %>% dplyr::select(-dplyr::starts_with("pagination")) } return(df) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/get_server_projects.R
#' Get extract refresh tasks from Tableau Server. #' #' Retrieves a list of extract refresh tasks from the Tableau Server using the provided authentication credentials. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, `user_id`, and `site_id`. #' @param api_version The API version to use (default: 3.4). #' @param page_size The number of records to retrieve per page (default: 100). #' #' @return A data frame containing the extract refresh tasks information. #' @export #' #' @family Tableau REST API get_server_refresh_tasks <- function(tableau, api_version = 3.4, page_size = 100) { base_url <- tableau$base_url token <- tableau$token site_id <- tableau$site_id url <- paste0( base_url, "api/", api_version, "/sites/", site_id, "/tasks/extractRefreshes?fields=_all_&pageSize=", page_size ) api_response <- httr::GET( url, httr::add_headers("X-Tableau-Auth" = token) ) jsonResponseText <- httr::content(api_response, as = "text") df <- as.data.frame(jsonlite::fromJSON(jsonResponseText)) %>% tidyr::unnest() return(df) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/get_server_refresh_tasks.R
#' Get schedules from Tableau server. #' #' Retrieves a list of schedules from the Tableau server using the provided authentication credentials. #' #' @param tableau A list containing the Tableau authentication variables: `base_url` and `token`. #' @param api_version The API version to use (default: 3.4). #' @param page_number The page number of the results to retrieve (default: 1). #' @param page_size The number of records to retrieve per page (default: 100). #' @param include_metadata Logical indicating whether to include metadata columns in the result (default: FALSE). #' #' @return A data frame containing the schedules information. #' @export #' #' @family Tableau REST API get_server_schedules <- function(tableau, api_version = 3.4, page_number = 1, page_size = 100, include_metadata = FALSE) { base_url <- tableau$base_url token <- tableau$token url <- paste0( base_url, "api/", api_version, "/schedules?fields=_all_&pageSize=", page_size, "&pageNumber=", page_number ) api_response <- httr::GET( url, httr::add_headers("X-Tableau-Auth" = token) ) jsonResponseText <- httr::content(api_response, as = "text") df <- jsonlite::fromJSON(jsonResponseText) %>% as.data.frame() %>% dplyr::rename_with(~ stringr::str_remove(., "schedules.schedule."), dplyr::everything()) if (!include_metadata) { df <- df %>% dplyr::select(-dplyr::starts_with("pagination")) } return(df) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/get_server_schedules.R
#' Get favorites for a user from Tableau Server. #' #' Retrieves a list of favorite projects, data sources, views, workbooks, and flows for a specific user on Tableau Server. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, `user_id`, and `site_id`. #' @param user_id The ID of the user for which you want to retrieve the favorites. #' @param api_version The API version to use (default: 3.4). #' @param page_size The number of items to return in one response (default: 100). #' @param page_number The offset for paging (default: 1). #' #' @return A data frame containing the favorites for the specified user. #' @export #' #' @family Tableau REST API get_server_user_favorites <- function(tableau, user_id, api_version = 3.4, page_size = 100, page_number = 1) { base_url <- tableau$base_url token <- tableau$token site_id <- tableau$site_id # Construct the URL for retrieving user favorites url <- paste0( base_url, "api/", api_version, "/sites/", site_id, "/favorites/", user_id, "?pageSize=", page_size, "&pageNumber=", page_number ) # Make the API request api_response <- httr::GET( url, httr::add_headers("X-Tableau-Auth" = token) ) # Parse the JSON response jsonResponseText <- httr::content(api_response, as = "text") # Convert the JSON response to a data frame df <- as.data.frame(jsonlite::fromJSON(jsonResponseText), check.names = FALSE) %>% tidyr::unnest(names_sep = ".") %>% dplyr::rename_with(~ stringr::str_remove(., "favorites."), dplyr::everything()) return(df) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/get_server_user_favorites.R
#' Get users from Tableau server. #' #' Retrieves a list of users from the Tableau server using the provided authentication credentials. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, `user_id`, and `site_id`. #' @param api_version The API version to use (default: 3.4). #' @param page_number The page number of the results to retrieve (default: 1). #' @param page_size The number of users to retrieve per page (default: 100). #' @param include_metadata Logical indicating whether to include metadata columns in the result (default: FALSE). #' #' @return A data frame containing the users information. #' @export #' #' @family Tableau REST API get_server_users <- function(tableau, api_version = 3.4, page_number = 1, page_size = 100, include_metadata = FALSE) { base_url <- tableau$base_url token <- tableau$token site_id <- tableau$site_id url <- paste0( base_url, "api/", api_version, "/sites/", site_id, "/users?fields=_all_&pageSize=", page_size, "&pageNumber=", page_number ) api_response <- httr::GET( url, httr::add_headers("X-Tableau-Auth" = token) ) jsonResponseText <- httr::content(api_response, as = "text") df <- jsonlite::fromJSON(jsonResponseText) %>% as.data.frame(check.names = FALSE) %>% dplyr::rename_with(~ stringr::str_remove(., "users.user."), dplyr::everything()) if (!include_metadata) { df <- df %>% dplyr::select(-dplyr::starts_with("pagination")) } return(df) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/get_server_users.R
#' Get views from Tableau server. #' #' Retrieves a list of views from the Tableau server using the provided authentication credentials. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, `user_id`, and `site_id`. #' @param api_version The API version to use (default: 3.4). #' @param page_number The page number of the results to retrieve (default: 1). #' @param page_size The number of views to retrieve per page (default: 100). #' @param include_statistics Logical indicating whether to include usage statistics in the result (default: TRUE). #' @param include_metadata Logical indicating whether to include metadata columns in the result (default: FALSE). #' #' @return A data frame containing the views information. #' @export #' #' @family Tableau REST API get_server_views <- function(tableau, api_version = 3.4, page_number = 1, page_size = 100, include_statistics = TRUE, include_metadata = FALSE) { base_url <- tableau$base_url token <- tableau$token site_id <- tableau$site_id url <- paste0( base_url, "api/", api_version, "/sites/", site_id, "/views?fields=_all_&includeUsageStatistics=", include_statistics, "&pageSize=", page_size, "&pageNumber=", page_number ) api_response <- httr::GET( url, httr::add_headers("X-Tableau-Auth" = token) ) jsonResponseText <- httr::content(api_response, as = "text") df <- jsonlite::fromJSON(jsonResponseText) %>% as.data.frame(check.names = FALSE) %>% dplyr::rename_with(~ stringr::str_remove(., "views.view."), dplyr::everything()) if (!include_metadata) { df <- df %>% dplyr::select(-dplyr::starts_with("pagination")) } return(df) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/get_server_views.R
#' Get workbooks from Tableau server. #' #' Retrieves a list of workbooks from the Tableau server using the provided authentication credentials. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, `user_id`, and `site_id`. #' @param api_version The API version to use (default: 3.4). #' @param page_number The page number of the results to retrieve (default: 1). #' @param page_size The number of workbooks to retrieve per page (default: 100). #' @param include_metadata Logical indicating whether to include metadata columns in the result (default: FALSE). #' #' @return A data frame containing the workbooks information. #' @export #' #' @family Tableau REST API get_server_workbooks <- function(tableau, api_version = 3.4, page_number = 1, page_size = 100, include_metadata = FALSE) { base_url <- tableau$base_url token <- tableau$token site_id <- tableau$site_id url <- paste0( base_url, "api/", api_version, "/sites/", site_id, "/workbooks?fields=_all_&pageSize=", page_size, "&pageNumber=", page_number ) api_response <- httr::GET( url, httr::add_headers("X-Tableau-Auth" = token) ) jsonResponseText <- httr::content(api_response, as = "text") df <- jsonlite::fromJSON(jsonResponseText) %>% as.data.frame(check.names = FALSE) %>% tidyr::unnest(names_sep = ".") %>% dplyr::rename_all(~ stringr::str_remove(., "workbooks.workbook.")) if (!include_metadata) { df <- df %>% dplyr::select(-dplyr::starts_with("pagination")) } return(df) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/get_server_workbooks.R
#' Get table assets from Tableau Server. #' #' Retrieves information about all table assets for a site from the Tableau Server using the provided authentication credentials. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, `user_id`, and `site_id`. #' @param api_version The API version to use (default: 3.8). #' #' @return A data frame containing the table assets information. #' @export #' #' @family Tableau REST API get_table_assets <- function(tableau, api_version = 3.8) { base_url <- tableau$base_url token <- tableau$token site_id <- tableau$site_id url <- paste0( base_url, "api/", api_version, "/sites/", site_id, "/tables" ) api_response <- httr::GET( url, httr::add_headers("X-Tableau-Auth" = token) ) jsonResponseText <- httr::content(api_response, as = "text") df <- as.data.frame(jsonlite::fromJSON(jsonResponseText), check.names = FALSE) return(df) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/get_table_assets.R
#' Get Tableau data source #' #' Search XML for data source of Tableau workbook #' #' @param dashboard Path to Tableau twb file. #' #' @return Data source of the workbook #' @export #' @family xml #' @examples #' \dontrun{ #' # Get Tableau data source #' data_source <- get_tableau_data_source(dashboard = "path/to/workbook.twb") #' print(data_source) #' } get_tableau_data_source <- function(dashboard) { data <- xml2::read_xml(dashboard) data_source <- xml2::xml_find_all(data, "//@filename") return(xml2::xml_text(data_source)) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/get_tableau_data_source.R
#' Get Users in Group #' #' Gets a list of users in the specified group. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, `user_id`, and `site_id`. #' @param api_version The version of the API to use, such as 3.21. #' @param group_id The ID of the group to get the users for. #' @param page_size The number of items to return in one response. The minimum is 1. The maximum is 1000. The default is 100. #' @param page_number The offset for paging. The default is 1. #' #' @return A list of users in the specified group. #' @export #' #' @family Tableau REST API get_users_in_group <- function(tableau, api_version = 3.19, group_id, page_size = 100, page_number = 1) { base_url <- tableau$base_url site_id <- tableau$site_id token <- tableau$token url <- paste0( base_url, "api/", api_version, "/sites/", site_id, "/groups/", group_id, "/users", "?pageSize=", page_size, "&pageNumber=", page_number ) api_response <- httr::GET( url, httr::add_headers("X-Tableau-Auth" = token) ) # Check the response status code if (httr::status_code(api_response) != 200) { stop("Failed to get users in group. Please check your API key and base URL.") } jsonResponseText <- httr::content(api_response, as = "text") users <- jsonlite::fromJSON(jsonResponseText)$users$user return(users) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/get_users_in_group.R
#' Get folder names #' #' @param wb The path to the Tableau workbook file [.twb]. #' #' @return Dataframe containing the variable folder names #' @export #' #' @family xml get_variable_folders <- function(wb) { proc <- make_rootnodes(wb) nodenames <- get_nodenames(proc) xy <- which(nodenames == "datasources") cc <- XML::getNodeSet(proc[[xy]], ".//folder") df <- data.table::rbindlist(lapply(cc, function(x) { r <- t(XML::xpathSApply(x, ".", XML::xmlAttrs)) data.frame(r) }), fill = TRUE) return(df) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/get_variable_folders.R
#' Get variable names from workbook. #' #' @param wb The path to the Tableau workbook file [.twb]. #' #' @return Dataframe #' @export #' #' @family xml get_variables <- function(wb) { proc <- make_rootnodes(wb) nodenames <- get_nodenames(proc) xy <- which(nodenames == "datasources") var_ordinal <- XML::xpathSApply(proc[[xy]], "//workbook//datasource//column", XML::xmlGetAttr, "ordinal") var_caption <- XML::xpathSApply(proc[[xy]], "//workbook//datasource//column", XML::xmlGetAttr, "caption") var_data_type <- XML::xpathSApply(proc[[xy]], "//workbook//datasource//column", XML::xmlGetAttr, "datatype") var_format <- XML::xpathSApply(proc[[xy]], "//workbook//datasource//column", XML::xmlGetAttr, "default-format") var_name <- XML::xpathSApply(proc[[xy]], "//workbook//datasource//column", XML::xmlGetAttr, "name") var_role <- XML::xpathSApply(proc[[xy]], "//workbook//datasource//column", XML::xmlGetAttr, "role") var_type <- XML::xpathSApply(proc[[xy]], "//workbook//datasource//column", XML::xmlGetAttr, "type") par_value <- XML::xpathSApply(proc[[xy]], "//workbook//datasource//column", XML::xmlGetAttr, "value") ## TEMP: get nested xml tags utilFun <- function(x) { attributess <- list(sapply(XML::xmlChildren(x, omitNodeTypes = "XMLInternalTextNode"), XML::xmlAttrs)) } result <- XML::xpathApply(proc[[xy]], "//workbook//datasource//column", utilFun) nested_xml <- do.call(rbind, result) df <- data.frame( var_name, nested_xml ) %>% tidyr::unnest_wider(nested_xml) %>% dplyr::mutate( role = var_role, ordinal = var_ordinal, caption = var_caption, datatype = var_data_type, format = var_format, thetype = var_type, thevalue = par_value ) return(df) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/get_variables.R
#' Get workbook ID name. #' #' @param wb The path to the Tableau workbook [.twb]. #' #' @return The ID name of the workbook. #' @export #' #' @family xml get_workbook_id <- function(wb) { proc <- make_rootnodes(wb) nodenames <- get_nodenames(proc) xy <- which(nodenames == "repository-location") ID <- cbind(XML::xpathSApply(proc[[xy]], ".", XML::xmlGetAttr, "id")) return(as.character(ID)) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/get_workbook_id.R
#' Get workbook tabs #' #' @param wb The path to the Tableau workbook file [.twb]. #' #' @return Dataframe #' @export #' #' @family xml get_workbook_tabs <- function(wb) { proc <- make_rootnodes(wb) nodenames <- get_nodenames(proc) xy <- which(nodenames == "windows") tab_name <- XML::xpathSApply(proc[[xy]], ".//window", XML::xmlGetAttr, "name") tab_type <- XML::xpathSApply(proc[[xy]], ".//window", XML::xmlGetAttr, "class") hidden <- cbind(XML::xpathSApply(proc[[xy]], ".//window", XML::xmlGetAttr, "hidden")) tab_color <- cbind(XML::xpathSApply(proc[[xy]], ".//window", XML::xmlGetAttr, "tab-color")) dfWorksheets <- data.table::data.table(data.frame(tab_name, tab_type, hidden, tab_color)) return(dfWorksheets) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/get_workbook_tabs.R
#' Get Workbook URLs #' #' This function parses an XML document representing a Tableau workbook and finds all nodes that have a url attribute containing 'views'. #' It then extracts these URLs and returns them in a data frame. #' #' @param wb The path to the Tableau workbook file (.twb). #' #' @return A data frame containing the URLs found in the workbook. #' @export get_workbook_urls <- function(wb) { # Parse the XML document doc <- XML::xmlParse(wb) # Get the root node root <- XML::xmlRoot(doc) # Find all nodes that have a url attribute containing 'views' nodes <- XML::xpathSApply(root, "//*[contains(@url, 'views')]") # Initialize an empty vector to store the URLs urls <- character(length(nodes)) # Loop over the nodes for (i in seq_along(nodes)) { # Extract the URL attribute url <- XML::xmlGetAttr(nodes[[i]], "url") # Store the URL in the urls vector urls[i] <- url } # Convert the urls vector to a data frame dfUrls <- data.frame(URL = urls) return(dfUrls) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/get_workbook_urls.R
#' make_rootnodes #' #' @param wb The path to the tableau workbook file [.twb]. #' #' @return The rootnodes. #' @export #' #' @family xml make_rootnodes <- function(wb) { tempd <- tempdir() fext <- paste0(".", sub(".*\\.", "", wb)) tmpf <- tempfile(tmpdir = tempd, fileext = fext) file.copy(wb, tmpf) filed <- sub(pattern = fext, ".xml", tmpf) file.rename(tmpf, filed) rootnode <- XML::xmlRoot(XML::xmlParse(file = filed)) unlink("tempd", recursive = TRUE) return(rootnode) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/make_rootnodes.R
#' Query User On Site #' #' Returns information about the specified user. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, and `site_id`. #' @param user_id The ID of the user to get information for. #' @param api_version The API version to use (default: 3.19). #' #' @return Information about the specified user. #' @export #' @family Tableau REST API query_user_on_site <- function(tableau, user_id, api_version = 3.19) { base_url <- tableau$base_url token <- tableau$token site_id <- tableau$site_id url <- paste0( base_url, "/api/", api_version, "/sites/", site_id, "/users/", user_id ) api_response <- httr::GET( url, httr::add_headers("X-Tableau-Auth" = token) ) # Check the response status code if (httr::status_code(api_response) != 200) { stop("Failed to query user on site. Please check your API key and base URL.") } jsonResponseText <- httr::content(api_response, as = "text") user_info <- jsonlite::fromJSON(jsonResponseText) %>% as.data.frame(check.names = FALSE) return(user_info) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/query_user_on_site.R
#' Remove User from Group #' #' Removes a user from the specified group. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, `user_id`, and `site_id`. #' @param api_version The version of the API to use, such as 3.19 (default: 3.19). #' @param group_id The ID of the group to remove the user from. #' @param user_id The ID of the user to remove. #' #' @return The response from the API. #' @export #' @family Tableau REST API remove_user_from_group <- function(tableau, api_version = 3.19, group_id, user_id) { base_url <- tableau$base_url site_id <- tableau$site_id token <- tableau$token url <- paste0( base_url, "api/", api_version, "/sites/", site_id, "/groups/", group_id, "/users/", user_id ) api_response <- httr::DELETE( url, httr::add_headers("X-Tableau-Auth" = token) ) return(api_response) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/remove_user_from_group.R
#' Remove User from Site #' #' Removes a user from the specified site. The user will be deleted if they do not own any other assets other than subscriptions. If a user still owns content (assets) on Tableau Server, the user cannot be deleted unless the ownership is reassigned first. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, `user_id`, and `site_id`. #' @param api_version The version of the API to use, such as 3.19 (default: 3.19). #' @param user_id The ID of the user to remove. #' @param mapAssetsTo Optional. The ID of a user that receives ownership of contents of the user being removed. #' #' @return No return value. #' @export #' #' @family Tableau REST API remove_user_from_site <- function(tableau, api_version = 3.19, user_id, mapAssetsTo = NULL) { base_url <- tableau$base_url token <- tableau$token site_id <- tableau$site_id url <- paste0( base_url, "api/", api_version, "/sites/", site_id, "/users/", user_id ) if (!is.null(mapAssetsTo)) { url <- paste0(url, "?mapAssetsTo=", mapAssetsTo) } httr::DELETE( url, httr::add_headers("X-Tableau-Auth" = token) ) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/remove_user_from_site.R
#' Run Extract Refresh Task #' #' Runs the specified extract refresh task on Tableau Server. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, and `site_id`. #' @param task_id The ID of the extract refresh task to run. #' @param api_version The API version to use (default: 3.22). #' #' @return The response from the API. #' @export #' #' @family Tableau REST API run_extract_refresh_task <- function(tableau, task_id, api_version = 3.22) { base_url <- tableau$base_url token <- tableau$token site_id <- tableau$site_id url <- paste0( base_url, "api/", api_version, "/sites/", site_id, "/tasks/extractRefreshes/", task_id, "/runNow" ) # Construct the request body # As per the requirements, the request body can be empty for now request_body <- "<tsRequest></tsRequest>" # Make the POST request to the Tableau REST API api_response <- httr::POST( url, httr::add_headers("X-Tableau-Auth" = token), body = request_body ) return(api_response) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/run_extract_refresh_task.R
#' Update Data Source Now #' #' Runs an extract refresh on the specified data source. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, and `site_id`. #' @param datasource_id The ID of the data source to refresh. #' @param api_version The API version to use (default: 3.22). #' #' @return The response from the API. #' @export #' #' @family Tableau REST API update_data_source_now <- function(tableau, datasource_id, api_version = 3.22) { base_url <- tableau$base_url token <- tableau$token site_id <- tableau$site_id url <- paste0( base_url, "api/", api_version, "/sites/", site_id, "/datasources/", datasource_id, "/refresh" ) # Construct the request body # The request body is empty as per the requirements request_body <- "<tsRequest></tsRequest>" # Make the POST request to the Tableau REST API api_response <- httr::POST( url, httr::add_headers("X-Tableau-Auth" = token), body = request_body ) return(api_response) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/update_data_source_now.R
#' Update Group #' #' Updates a group on a Tableau Server or Tableau Cloud site. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, and `site_id`. #' @param group_id The ID of the group to update. #' @param group_name The new name for the group (optional). #' @param AD_group_name The name of the Active Directory group to synchronize with (optional). #' @param AD_domain The domain for the Active Directory group (optional). #' @param minimum_site_role Required if an import element or grantLicenseMode attribute are present in the request. The site role assigned to users who are imported from Active Directory or granted a license automatically using the grant license on-sync or on-login mode. #' @param license_mode Optional. The mode for automatically applying licenses for group members. When the mode is onLogin, a license is granted for each group member when they log in to a site. #' @param on_demand_access Optional. A boolean value that is used to enable on-demand access for embedded Tableau content when the Tableau Cloud site is licensed with Embedded Analytics usage-based model. #' @param asJob A Boolean value indicating whether to synchronize with Active Directory as a background task (true) or synchronize immediately (false). Default is false. #' @param api_version The API version to use (default: 3.19). #' #' @return TRUE if the operation was successful, FALSE otherwise. #' @export #' #' @family Tableau REST API update_group <- function(tableau, group_id, group_name = NULL, AD_group_name = NULL, AD_domain = NULL, minimum_site_role = NULL, license_mode = NULL, on_demand_access = NULL, asJob = FALSE, api_version = 3.19) { base_url <- tableau$base_url token <- tableau$token site_id <- tableau$site_id url <- paste0( base_url, "/api/", api_version, "/sites/", site_id, "/groups/", group_id, if (asJob) "?asJob=true" else "" ) # Construct the request body request_body <- paste0( "<tsRequest>", "<group ", if (!is.null(group_name)) paste0("name=\"", group_name, "\" "), if (!is.null(AD_group_name)) paste0("AD-group-name=\"", AD_group_name, "\" "), if (!is.null(AD_domain)) paste0("AD-domain=\"", AD_domain, "\" "), if (!is.null(minimum_site_role)) paste0("minimum-site-role=\"", minimum_site_role, "\" "), if (!is.null(license_mode)) paste0("license-mode=\"", license_mode, "\" "), if (!is.null(on_demand_access)) paste0("on-demand-access=\"", on_demand_access, "\" "), "/>", "</tsRequest>" ) api_response <- httr::PUT( url, httr::add_headers("X-Tableau-Auth" = token), body = request_body ) # Check the response status code if (httr::status_code(api_response) != 200) { stop("Group update failed. Please check your API key and base URL.") } return(TRUE) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/update_group.R
#' Update User #' #' Modifies information about the specified user. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, and `site_id`. #' @param user_id The ID of the user to update. #' @param fullName The new name for the user (optional). #' @param email The new email address for the user (optional). #' @param password The new password for the user (optional). #' @param siteRole The new site role to assign to the user. #' @param authSetting The authentication type for the user (optional). #' @param api_version The API version to use (default: 3.19). #' #' @return TRUE if the operation was successful, FALSE otherwise. #' @export #' #' @family Tableau REST API update_user <- function(tableau, user_id, fullName = NULL, email = NULL, password = NULL, siteRole, authSetting = NULL, api_version = 3.19) { base_url <- tableau$base_url token <- tableau$token site_id <- tableau$site_id url <- paste0( base_url, "/api/", api_version, "/sites/", site_id, "/users/", user_id ) # Construct the request body request_body <- paste0( "<tsRequest>", "<user ", if (!is.null(fullName)) paste0("fullName=\"", fullName, "\" "), if (!is.null(email)) paste0("email=\"", email, "\" "), if (!is.null(password)) paste0("password=\"", password, "\" "), "siteRole=\"", siteRole, "\" ", if (!is.null(authSetting)) paste0("authSetting=\"", authSetting, "\" "), "/>", "</tsRequest>" ) api_response <- httr::PUT( url, httr::add_headers("X-Tableau-Auth" = token), body = request_body ) # Check the response status code if (httr::status_code(api_response) != 200) { stop("User update failed. Please check your API key and base URL.") } return(TRUE) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/update_user.R
#' Update Workbook Now #' #' Refreshes the specified workbook. #' #' @param tableau A list containing the Tableau authentication variables: `base_url`, `token`, and `site_id`. #' @param workbook_id The ID of the workbook to refresh. #' @param api_version The API version to use (default: 3.22). #' #' @return The response from the API. #' @export #' #' @family Tableau REST API update_workbook_now <- function(tableau, workbook_id, api_version = 3.22) { base_url <- tableau$base_url token <- tableau$token site_id <- tableau$site_id url <- paste0( base_url, "api/", api_version, "/sites/", site_id, "/workbooks/", workbook_id, "/refresh" ) # Construct the request body # The request body is empty as per the requirements request_body <- "<tsRequest></tsRequest>" # Make the POST request to the Tableau REST API api_response <- httr::POST( url, httr::add_headers("X-Tableau-Auth" = token), body = request_body ) return(api_response) }
/scratch/gouwar.j/cran-all/cranData/vvtableau/R/update_workbook_now.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/vvtableau/R/utils-pipe.R
## ----include = FALSE---------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>", eval = FALSE ) ## ----setup-------------------------------------------------------------------- # library(vvtableau) # # # Authenticate on the Tableau Server. # tableau <- authenticate_server( # server = "https://tableau.server.com", # username = "your_username", # password = "your_password" # ) # # # Set the view ID for the Super Sample Superstore example view # view_id <- "super-sample-superstore-view-id" # # # Set the path to save the downloaded images # path_to_save <- "path/to/save/images/" ## ----config------------------------------------------------------------------- # # Create a dataframe with the filter values for each combination # filter_df <- data.frame( # region = c("West", "East", "Central"), # category = c("Furniture", "Technology", "Office Supplies") # ) # # download_filtered_tableau_image(tableau, filter_df, view_id, path_to_save) # #
/scratch/gouwar.j/cran-all/cranData/vvtableau/inst/doc/download_filtered_views.R
--- title: "Downloading Filtered Tableau Images with Super Sample Superstore" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Downloading Filtered Tableau Images with Super Sample Superstore} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", eval = FALSE ) ``` # Introduction This vignette demonstrates the usage of the `download_filtered_tableau_image` function in the R package. We'll use the Super Sample Superstore example in Tableau to showcase how to download filtered images by filtering on various combinations of region and category. ```{r setup} library(vvtableau) # Authenticate on the Tableau Server. tableau <- authenticate_server( server = "https://tableau.server.com", username = "your_username", password = "your_password" ) # Set the view ID for the Super Sample Superstore example view view_id <- "super-sample-superstore-view-id" # Set the path to save the downloaded images path_to_save <- "path/to/save/images/" ``` # Download Filtered Images Let's download images for different combinations of region and category filters. ```{r config} # Create a dataframe with the filter values for each combination filter_df <- data.frame( region = c("West", "East", "Central"), category = c("Furniture", "Technology", "Office Supplies") ) download_filtered_tableau_image(tableau, filter_df, view_id, path_to_save) ``` For this example, the function will iterate over each row of the dataframe and download the filtered images for each combination of region and category. In this case, it will download images for the following combinations: - "West" region, "Furniture" category - "East" region, "Technology" category - "Central" region, "Office Supplies" category You can customize the `filter_df` dataframe to include more combinations of region and category filters as needed.
/scratch/gouwar.j/cran-all/cranData/vvtableau/inst/doc/download_filtered_views.Rmd
## ----include = FALSE---------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, eval = FALSE, comment = "#>" ) ## ----setup-------------------------------------------------------------------- # library(vvtableau) ## ----authenticate------------------------------------------------------------- # tableau <- authenticate_server( # server = "https://tableau.server.com", # username = "your_username", # password = "your_password" # ) ## ----jobs--------------------------------------------------------------------- # get_server_jobs( # tableau, # page_size = 300 # )
/scratch/gouwar.j/cran-all/cranData/vvtableau/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 `vvtableau` package provides an interface for interacting with Tableau Server using the Tableau REST API. This vignette will walk you through the main functionalities of the package, demonstrating how to authenticate, retrieve information, and perform various operations on Tableau Server. ```{r setup} library(vvtableau) ``` # Authentication To begin, you need to authenticate and establish a connection to Tableau Server. Use the authenticate_server() function to provide the server URL, your username, and password. Here's an example: ```{r authenticate} tableau <- authenticate_server( server = "https://tableau.server.com", username = "your_username", password = "your_password" ) ``` When authentication has succeeded the `tableau` object can be passed to the Tableau REST API methods. # Retrieving Server Information Once connected, you can retrieve various information about Tableau Server using the provided functions. Here is an example to retrieve the jobs on the server: ```{r jobs} get_server_jobs( tableau, page_size = 300 ) ``` # Conclusion This vignette covered the basic functionalities of the `vvtableau` package, including authentication, retrieving server information, publishing workbooks, managing users and groups, and downloading workbooks and views. For a complete list of functions and their parameters, please refer to the package documentation. Please note that this vignette serves as a brief introduction to the package and its capabilities. For more detailed instructions and examples, consult the package documentation and explore the individual function documentation. We hope you find the `vvtableau` package helpful in automating your Tableau workflows and enhancing your Tableau Server experience!
/scratch/gouwar.j/cran-all/cranData/vvtableau/inst/doc/getting_started.Rmd
--- title: "Downloading Filtered Tableau Images with Super Sample Superstore" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Downloading Filtered Tableau Images with Super Sample Superstore} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", eval = FALSE ) ``` # Introduction This vignette demonstrates the usage of the `download_filtered_tableau_image` function in the R package. We'll use the Super Sample Superstore example in Tableau to showcase how to download filtered images by filtering on various combinations of region and category. ```{r setup} library(vvtableau) # Authenticate on the Tableau Server. tableau <- authenticate_server( server = "https://tableau.server.com", username = "your_username", password = "your_password" ) # Set the view ID for the Super Sample Superstore example view view_id <- "super-sample-superstore-view-id" # Set the path to save the downloaded images path_to_save <- "path/to/save/images/" ``` # Download Filtered Images Let's download images for different combinations of region and category filters. ```{r config} # Create a dataframe with the filter values for each combination filter_df <- data.frame( region = c("West", "East", "Central"), category = c("Furniture", "Technology", "Office Supplies") ) download_filtered_tableau_image(tableau, filter_df, view_id, path_to_save) ``` For this example, the function will iterate over each row of the dataframe and download the filtered images for each combination of region and category. In this case, it will download images for the following combinations: - "West" region, "Furniture" category - "East" region, "Technology" category - "Central" region, "Office Supplies" category You can customize the `filter_df` dataframe to include more combinations of region and category filters as needed.
/scratch/gouwar.j/cran-all/cranData/vvtableau/vignettes/download_filtered_views.Rmd