diff --git a/DESCRIPTION b/DESCRIPTION index 026d520..9cc39bf 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -2,7 +2,7 @@ Package: consequencestools Type: Package Title: Provides Support Tools for Data Analysis and Visualization from the Ultimate Consequences Database -Version: 0.0.0.9011 +Version: 0.0.0.9012 Authors@R: person( "Carwil", "Bjork-James", @@ -31,6 +31,8 @@ Imports: ggplot2, grDevices, incase, + janitor, + kableExtra, lubridate, magrittr, purrr, diff --git a/NAMESPACE b/NAMESPACE index dd1e510..591d749 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -57,6 +57,7 @@ export(id_for_event) export(id_for_municipality) export(id_for_municipality_2) export(id_for_president) +export(insert_rows_by_group_vars) export(make_waffle_chart) export(make_waffle_chart_tall) export(muni_counts_by) @@ -93,6 +94,8 @@ export(sv_pal) export(top_values_string) export(truncate_event_list) export(truncate_muni_list) +export(two_layer_frequency_kable) +export(two_layer_frequency_table) export(waffle_counts) export(wide_event_outcomes_reactable) export(wide_event_outcomes_table) @@ -142,6 +145,11 @@ importFrom(grDevices,col2rgb) importFrom(grDevices,colorRamp) importFrom(grDevices,rgb) importFrom(incase,in_case) +importFrom(janitor,adorn_pct_formatting) +importFrom(janitor,tabyl) +importFrom(kableExtra,kable_classic) +importFrom(kableExtra,kbl) +importFrom(kableExtra,row_spec) importFrom(lubridate,days) importFrom(lubridate,ymd) importFrom(magrittr,"%>%") diff --git a/R/aaa-data.R b/R/aaa-data.R index 856bae4..0378641 100644 --- a/R/aaa-data.R +++ b/R/aaa-data.R @@ -116,8 +116,8 @@ #' @format A tibble with multiple columns including unqiue identifiers in #' `presidency` (the levels of pres_admin in English) and `presidency_id` #' (a unique identifier in the format "p104"). `first_day` and `last_day` -#' are dates indicating the term of offfice of each president. -#' +#' are dates indicating the term of office of each president. The +#' `last_day` of the most recent presidency is set to NA. "presidency_name_table" #' Helper variable for levels of state responsibility diff --git a/R/consequencestools-package.R b/R/consequencestools-package.R index d49642a..9ec9eb3 100644 --- a/R/consequencestools-package.R +++ b/R/consequencestools-package.R @@ -42,6 +42,11 @@ #' @importFrom grDevices colorRamp #' @importFrom grDevices rgb #' @importFrom incase in_case +#' @importFrom janitor adorn_pct_formatting +#' @importFrom janitor tabyl +#' @importFrom kableExtra kable_classic +#' @importFrom kableExtra kbl +#' @importFrom kableExtra row_spec #' @importFrom lubridate days #' @importFrom reactable colDef #' @importFrom reactablefmtr nytimes diff --git a/R/freq-table-hierarchical.R b/R/freq-table-hierarchical.R new file mode 100644 index 0000000..cbd57b9 --- /dev/null +++ b/R/freq-table-hierarchical.R @@ -0,0 +1,304 @@ +globalVariables(c("n_2", "pct", "n", "is_first_in_group", + "variable1_display", "n_display", "pct_display")) +#' Insert rows into a grouped table from an additional dataframe +#' +#' @description +#' Insert rows from `additional_df` into `main_df` by matching groups defined +#' by `variable1`. For each unique value of `variable1` in `main_df`, if a +#' corresponding row exists in `additional_df` it will be appended to that +#' group's rows. Any `variable1` values that appear only in `additional_df` +#' will be appended as new groups at the end of the returned data frame. +#' +#' This function uses tidy-eval for `variable1` and `variable2` (unquoted +#' column names). +#' +#' @param main_df A data.frame. The primary table containing the main groups. +#' @param additional_df A data.frame. Rows to be inserted into `main_df` by +#' matching on `variable1`. +#' @param variable1 Column name (unquoted) used as the grouping key (tidy-eval). +#' @param variable2 Column name (unquoted) indicating the second-level variable +#' to be inserted (tidy-eval). +#' +#' @return A data.frame containing rows from `main_df` with rows from +#' `additional_df` inserted by group. Rows from `additional_df` whose +#' `variable1` values do not exist in `main_df` will appear as new groups. +#' +#' @examples +#' df_main <- data.frame(group = c("A", "A", "B"), +#' sub = c("x", "y", "z"), n = 1:3, stringsAsFactors = FALSE) +#' df_add <- data.frame(group = c("A", "C"), +#' sub = c("other", "other"), n_2 = c(10, 5), stringsAsFactors = FALSE) +#' insert_rows_by_group_vars(df_main, df_add, group, sub) +#' +#' @seealso two_layer_frequency_table, two_layer_frequency_kable +#' @export +insert_rows_by_group_vars <- function(main_df, additional_df, variable1, variable2) { + result <- data.frame() + var1_name <- rlang::as_name(enquo(variable1)) + var2_name <- rlang::as_name(enquo(variable2)) + + # Get unique variable1 values from the main dataframe + unique_var1_values <- unique(main_df[[var1_name]]) + + # Process each group + for (var1_value in unique_var1_values) { + # Get rows for this var1_value from main dataframe + main_rows <- main_df[main_df[, var1_name] == var1_value, ] + + # Check if there are additional rows for this var1_value + if (var1_value %in% additional_df[[var1_name]]) { + # Get the other row that corresponds to this var1_value + other_row <- additional_df[additional_df[, var1_name] == var1_value, ] + + # Append the rows together + group_result <- bind_rows(main_rows, other_row) + } else { + group_result <- main_rows + } + + # Append to the result + result <- bind_rows(result, group_result) + } + + # Check if there are any values in additional_df that aren't in main_df + unique_other_var1_values <- setdiff(unique(additional_df[[var1_name]]), unique_var1_values) + + # Add these as new groups + if (length(unique_other_var1_values) > 0) { + for (var1_value in unique_other_var1_values) { + other_row <- additional_df[additional_df[, var1_name] == var1_value, ] + result <- bind_rows(result, other_row) + } + } + + # Return the combined result + return(result) +} + + +#' Two-layer frequency table (data) +#' +#' @description +#' Compute a two-layer frequency table (unformatted data) that contains primary +#' counts and percentages for `variable1` and the secondary breakdown by +#' `variable2`. This function returns the combined data.frame (ft.combined) +#' which can be further processed or passed to a kable/printing function. +#' +#' The `variable1` and `variable2` arguments use tidy-eval (unquoted column +#' names). +#' +#' @param dataset A data.frame. The input dataset. +#' @param variable1 Column name (unquoted) for the primary grouping variable +#' (tidy-eval). +#' @param variable2 Column name (unquoted) for the secondary grouping variable +#' (tidy-eval). +#' @param sort Logical. If TRUE, sort groups by descending counts. Default: +#' TRUE. +#' @param threshold Integer. Minimum count threshold for including a secondary +#' category. Secondary categories with counts below `threshold` will be +#' combined into an "Other" row. Default: 1. +#' +#' @return A data.frame (ft.combined) with columns for the primary variable, +#' counts (n), percentage (pct), secondary variable, and secondary counts +#' (n_2). +#' +#' @examples +#' library(dplyr) +#' mtcars2 <- mtcars %>% mutate(cyl = as.factor(cyl), gear = as.factor(gear)) +#' two_layer_frequency_table(mtcars2, cyl, gear, sort = TRUE, threshold = 1) +#' +#' @export +two_layer_frequency_table <- function(dataset, + variable1, + variable2, + sort=TRUE, + threshold = 1) { + # clear out NA values in the variables (warn if present) + if(n_filter(dataset, is.na({{variable1}}) > 0)) { + warning(paste("The dataset contains", n_filter(dataset, is.na({{variable1}})), + "rows with NA values in", rlang::as_name(enquo(variable1)), + "which will be excluded from the analysis.")) + } + if(n_filter(dataset, is.na({{variable2}}) > 0)) { + warning(paste("The dataset contains", n_filter(dataset, is.na({{variable2}})), + "rows with NA values in", rlang::as_name(enquo(variable2)), + "which will be excluded from the analysis.")) + } + + # Create primary table + ft.primary <- dataset %>% + janitor::tabyl({{variable1}}, show_na = FALSE) %>% + janitor::adorn_pct_formatting() %>% + rename("pct" = "percent") %>% + filter(n >= threshold) + + if (sort) { + ft.primary <- ft.primary %>% arrange(desc(n)) + } + + # Create secondary counts + ft.secondary <- dataset %>% + count({{variable1}}, {{variable2}}) %>% + rename("n_2" = "n") + + # Join tables + ft.combined <- left_join(ft.primary, ft.secondary, by = rlang::as_name(enquo(variable1))) + + if (sort) { + ft.combined <- ft.combined %>% arrange(desc(n), desc(n_2)) + } + + if (threshold > 1) { + ft.other <- ft.combined %>% + filter((n_2 < threshold)) %>% + group_by({{variable1}}) %>% + summarize(n_2 = sum(n_2)) %>% + mutate({{variable2}} := "Other", + n = ft.primary$n[match({{variable1}}, ft.primary[,1])], + pct = ft.primary$pct[match({{variable1}}, ft.primary[,1])] + ) %>% + relocate(n, pct, {{variable2}}, .after = {{variable1}}) + + # Filter out rows where n_2 is less than the threshold + ft.combined <- ft.combined %>% filter(n_2 >= threshold) + + # Combine the filtered rows with the "Other" rows + ft.combined_final <- insert_rows_by_group_vars(ft.combined, ft.other, {{variable1}}, {{variable2}}) + ft.combined <- ft.combined_final + } + + # Return the combined (unformatted) table + return(ft.combined) +} + + +#' Two-layer frequency table (formatted kable) +#' +#' @description +#' Create a formatted HTML kable from the two-layer frequency data. This +#' function calls two_layer_frequency_table() to compute the raw combined +#' table and then applies labeling, translation via transcats, and kableExtra +#' styling to produce a display-ready table. +#' +#' @param dataset A data.frame. The input dataset. +#' @param variable1 Column name (unquoted) for the primary grouping variable +#' (tidy-eval). +#' @param variable2 Column name (unquoted) for the secondary grouping variable +#' (tidy-eval). +#' @param sort Logical. If TRUE, sort groups by descending counts. Default: +#' TRUE. +#' @param threshold Integer. Minimum count threshold for including a secondary +#' category. Secondary categories with counts below `threshold` will be +#' combined into an "Other" row. Default: 1. +#' @param unit_is_deaths Logical. If TRUE, use "Deaths"/"Muertes" translation +#' for the secondary count label; otherwise use a generic "Numero"/"Count". +#' Default: TRUE. +#' +#' @return A kableExtra kable object (HTML) styled for reporting. +#' +#' @examples +#' library(dplyr) +#' mtcars2 <- mtcars %>% mutate(cyl = as.factor(cyl), gear = as.factor(gear)) +#' two_layer_frequency_kable(mtcars2, cyl, gear, sort = TRUE, threshold = 1) +#' +#' @export +two_layer_frequency_kable <- function(dataset, + variable1, + variable2, + sort=TRUE, + threshold = 1, + unit_is_deaths = TRUE) { + # Compute the combined data frame + ft.combined <- two_layer_frequency_table(dataset = dataset, + variable1 = {{variable1}}, + variable2 = {{variable2}}, + sort = sort, + threshold = threshold) + + # Recompute primary table (needed for total row) using same logic as the data function + ft.primary <- dataset %>% + janitor::tabyl({{variable1}}, show_na = FALSE) %>% + janitor::adorn_pct_formatting() %>% + rename("pct" = "percent") %>% + filter(n >= threshold) + + # Set knitr NA display option + options(knitr.kable.NA = '') + + # Manage translations via transcats + old_lang <- transcats::set_title_lang("en") + on.exit(transcats::set_title_lang(old_lang)) + + if (unit_is_deaths) { + n_secondary_trans_table <- tribble( + ~pct, ~n_2, ~language, + "% of Total", "Deaths", "en", + "%", "Muertes", "es", + "pct", "n_2", "r_variable" + ) + } else { + n_secondary_trans_table <- tribble( + ~pct, ~n_, ~n_2, ~language, + "% of Total", "Count", "Count", "en", + "%", "N\u00FAmero", "N\u00FAmero", "es", + "pct", "n_", "n_2", "r_variable" + ) + } + + uc_var_table_ext_2 <- transcats::append_to_var_name_table(n_secondary_trans_table, + transcats::uc_var_table_ext, + overwrite = TRUE) + transcats::set_var_name_table(uc_var_table_ext_2) + + + col.names = c(rlang::as_name(enquo(variable1)), "n_", "pct", + rlang::as_name(enquo(variable2)), "n_2") + n_2_total <- sum(ft.combined$n_2) + + output_kable <- ft.combined %>% + # Create a version of the dataset that has blank values for repeating cells + mutate( + # Create new columns for display that will have blanks for repeated values + variable1_display = as.character({{variable1}}), + n_display = n, + pct_display = pct + ) %>% + # Use group_by and row_number to identify repeats in the first column + group_by({{variable1}}) %>% + mutate( + # Only keep the first instance of each group, make others blank + variable1_display = ifelse(row_number() > 1, "", variable1_display), + n_display = ifelse(row_number() > 1, NA, n_display), + pct_display = ifelse(row_number() > 1, NA, pct_display), + # Create a flag for the first row of each group to add horizontal line + is_first_in_group = row_number() == 1 + ) %>% + mutate( + # Only keep the first instance of each group, make others blank + variable1_display = ifelse(is_first_in_group, variable1_display, "") + ) %>% + ungroup() %>% + # Create the table using the display columns + select(variable1_display, n_display, pct_display, {{variable2}}, n_2) %>% + add_row( + variable1_display := "Total", + n_display = sum(ft.primary$n), + pct_display = "100%", + {{variable2}} := "", + n_2 = n_2_total) %>% + # kbl(col.names = c("perp_affiliation", "n", "pct", "dec_affiliation", "n_2")) %>% + kableExtra::kbl(col.names = sapply(col.names, transcats::variable_name_from_string)) %>% + # Apply styling + kableExtra::kable_classic(full_width = F, html_font = "Minion Pro") %>% + # Add horizontal lines above each new group + kableExtra::row_spec(which(ft.combined %>% + group_by({{variable1}}) %>% + mutate(is_first_in_group = row_number() == 1) %>% + ungroup() %>% + pull(is_first_in_group)) %>% + c(nrow(ft.combined) + 1), + extra_css = "border-top: 1px solid black;") %>% + kableExtra::row_spec(c(0, nrow(ft.combined) + 1), bold = TRUE) + + return(output_kable) +} diff --git a/data-raw/level-variables.R b/data-raw/level-variables.R index 0ce8a39..109e9e2 100644 --- a/data-raw/level-variables.R +++ b/data-raw/level-variables.R @@ -10,25 +10,25 @@ president$levels <- c( "Gonzalo Sanchez de Lozada (1st)", "Hugo Banzer (2nd)", "Jorge Quiroga", "Gonzalo Sanchez de Lozada (2nd)", "Carlos Diego Mesa Gisbert", "Eduardo Rodríguez", "Evo Morales", "Interim military government", - "Jeanine Áñez", "Luis Arce") + "Jeanine Áñez", "Luis Arce", "Rodrigo Paz") president$initials <- c( "HSZ", "VPE", "JPZ", "GSL", "HB", "JQ", "GSL", "CM", "ER", "EM", "Mil", - "JA", "LA") + "JA", "LA", "RP") president$levels_es <- c( "Hernán Siles Zuazo", "Víctor Paz Estenssoro", "Jaime Paz Zamora", "Gonzalo Sanchez de Lozada (1ro)", "Hugo Banzer (2do)", "Jorge Quiroga", "Gonzalo Sanchez de Lozada (2do)", "Carlos Diego Mesa Gisbert", "Eduardo Rodríguez", "Evo Morales", "Interim military government", - "Jeanine Áñez", "Luis Arce") + "Jeanine Áñez", "Luis Arce", "Rodrigo Paz") president$id_presidency <- c( "p101", "p102", "p103", "p104", "p105", "p106", "p107", "p108", "p109", "p110", "p111", "p112", - "p113") + "p113", "p114") lev$pres_admin <- president diff --git a/data-raw/presidency-name-table.csv b/data-raw/presidency-name-table.csv index adbfb4e..8742cee 100644 --- a/data-raw/presidency-name-table.csv +++ b/data-raw/presidency-name-table.csv @@ -1,29 +1,30 @@ -presidency,id_presidency,presidency_year,presidency_commonname,presidency_fullname,presidency_surnames,presidency_year_es,presidency_commonname_es,presidency_fullname_es,presidency_initials,presidency_initials_num,first_day,last_day -René Barrientos,p86,René Barrientos (1964-1969),René Barrientos,René Barrientos Ortuño,Barrientos Ortuño,René Barrientos (1964-1969),René Barrientos,René Barrientos Ortuño,RB,RB,1964-11-05,1966-08-06 -Luis Adolfo Siles Salinas,p87,Luis Adolfo Siles Salinas (1969),Luis Adolfo Siles Salinas,Luis Adolfo Siles Salinas,Siles Salinas,Luis Adolfo Siles Salinas (1969),Luis Adolfo Siles Salinas,Luis Adolfo Siles Salinas,LAS,LAS,1966-08-06,1969-04-27 -Alfredo Ovando Candía,p88,Alfredo Ovando (1969-1970),Alfredo Ovando,Alfredo Ovando Candía,Ovando Candía,Alfredo Ovando (1969-1970),Alfredo Ovando,Alfredo Ovando Candía,AO,AO,1969-04-27,1969-09-26 -Juan José Torres,p89,Juan José Torres (1970-1971),Juan José Torres,Juan José Torres González,Torres González,Juan José Torres (1970-1971),Juan José Torres,Juan José Torres González,JJT,JJT,1970-10-07,1971-08-21 -Hugo Banzer (1st),p90,Hugo Banzer (1971-1978),Hugo Banzer,Hugo Banzer Suárez,Banzer Suárez,Hugo Banzer (1971-1978),Hugo Banzer,Hugo Banzer Suárez,HB,HB 1,1971-08-22,1978-07-21 -Juan Pereda,p91,Juan Pereda (1978),Juan Pereda,Juan Pereda Asbún,Pereda Asbún,Juan Pereda (1978),Juan Pereda,Juan Pereda Asbún,JP,JP,1978-07-21,1978-11-24 -David Padilla (Chairman of the Military Junta),p92,David Padilla (1978-1979),David Padilla,David Padilla Arancibia,Padilla Arancibia,David Padilla (1978-1979),David Padilla,David Padilla Arancibia,DP,DP,1978-11-24,1979-08-08 -Wálter Guevara,p93,Walter Guevara (1979),Walter Guevara,Wálter Guevara Arze,Guevara Arze,Walter Guevara (1979),Walter Guevara,Wálter Guevara Arze,WG,WG,1979-08-08,1979-11-01 -Alberto Natusch,p94,Alberto Natusch (1979),Alberto Natusch,Alberto Natusch Busch,Natusch Busch,Alberto Natusch (1979),Alberto Natusch,Alberto Natusch Busch,AN,AN,1979-11-01,1979-11-16 -Lydia Gueiler Tejada,p95,Lidia Gueiler (1979-1980),Lidia Gueiler,Lidia Gueiler Tejada,Gueiler Tejada,Lidia Gueiler (1979-1980),Lidia Gueiler,Lidia Gueiler Tejada,LG,LG,1979-11-17,1980-07-18 -Luis García Meza Tejada (2nd),p96,Luis García Meza (1980-1981),Luis García Meza,Luis García Meza Tejada,García Meza Tejada,Luis García Meza (1980-1981),Luis García Meza,Luis García Meza Tejada,LGM,LGM,1980-07-18,1981-08-04 -Junta of Commanders of the Armed Forces 1981,p97,Junta of Commanders of the Armed Forces (1981),Military Junta (1981),Junta of Commanders of the Armed Forces of the Nation,Junta of Commanders of the Armed Forces of the Nation,Junta Militar de Comandantes de las Fuerzas Armadas (1981),Military Junta (1981),Junta Militar de Comandantes de las Fuerzas Armadas ,Junta,Junta 1981,1981-08-04,1981-09-04 -Celso Torrelio,p98,Celso Torrelio (1981-1982),Celso Torrelio,Celso Torrelio Villa,Torrelio Villa,Celso Torrelio (1981-1982),Celso Torrelio,Celso Torrelio Villa,CT,CT,1981-09-04,1982-07-19 -Junta of Commanders of the Armed Forces 1982,p99,Junta of Commanders of the Armed Forces (1982),Military Junta (1982),Junta of Commanders of the Armed Forces of the Nation,Junta of Commanders of the Armed Forces of the Nation,Junta Militar de Comandantes de las Fuerzas Armadas (1982),Military Junta (1982),Junta Militar de Comandantes de las Fuerzas Armadas ,Junta,Junta 1982,1982-07-19,1982-07-21 -Guido Vildoso,p100,Guido Vildoso (1982),Guido Vildoso,Guido Vildoso Calderón,Vildoso Calderón,Guido Vildoso (1982),Guido Vildoso,Guido Vildoso Calderón,GV,GV,1982-07-21,1982-10-10 -Hernán Siles Zuazo,p101,Hernán Siles Zuazo (1982-1985),Hernán Siles Zuazo,Hernán Siles Zuazo,Siles Zuazo,Hernán Siles Zuazo (1982-1985),Hernán Siles Zuazo,Hernán Siles Zuazo,HSZ,HSZ,1982-10-10,1985-08-06 -Víctor Paz Estenssoro,p102,Víctor Paz Estenssoro (1985-1989),Víctor Paz Estenssoro,Víctor Paz Estenssoro,Paz Estenssoro,Víctor Paz Estenssoro (1985-1989),Víctor Paz Estenssoro,Víctor Paz Estenssoro,VPE,VPE 2,1985-08-06,1989-08-06 -Jaime Paz Zamora,p103,Jaime Paz Zamora (1989-1993),Jaime Paz Zamora,Jaime Paz Zamora,Paz Zamora,Jaime Paz Zamora (1989-1993),Jaime Paz Zamora,Jaime Paz Zamora,JPZ,JPZ,1989-08-06,1993-08-06 -Gonzalo Sanchez de Lozada (1st),p104,Gonzalo Sánchez de Lozada (1993-1997),Gonzalo Sánchez de Lozada,Gonzalo Sánchez de Lozada,Sánchez de Lozada,Gonzalo Sánchez de Lozada (1993-1997),Gonzalo Sánchez de Lozada,Gonzalo Sánchez de Lozada,GSL,GSL 1,1993-08-06,1997-08-06 -Hugo Banzer (2nd),p105,Hugo Banzer (1997-2001),Hugo Banzer,Hugo Banzer Suárez,Banzer Suárez,Hugo Banzer (1997-2001),Hugo Banzer,Hugo Banzer Suárez,HB,HB 2,1997-08-06,2001-08-07 -Jorge Quiroga,p106,Jorge Quiroga (2001-2002),Jorge Quiroga,Jorge Quiroga Ramírez,Quiroga Ramírez,Jorge Quiroga (2001-2002),Jorge Quiroga,Jorge Quiroga Ramírez,JQ,JQ,2001-08-07,2002-08-06 -Gonzalo Sanchez de Lozada (2nd),p107,Gonzalo Sánchez de Lozada (2002-2003),Gonzalo Sánchez de Lozada,Gonzalo Sánchez de Lozada,Sánchez de Lozada,Gonzalo Sánchez de Lozada (2002-2003),Gonzalo Sánchez de Lozada,Gonzalo Sánchez de Lozada,GSL,GSL 2,2002-08-06,2003-10-17 -Carlos Diego Mesa Gisbert,p108,Carlos Mesa (2003-2005),Carlos Mesa,Carlos Diego Mesa Gisbert,Mesa Gisbert,Carlos Mesa (2003-2005),Carlos Mesa,Carlos Diego Mesa Gisbert,CM,CM,2003-10-17,2005-06-09 -Eduardo Rodríguez,p109,Eduardo Rodríguez (2005-2006),Eduardo Rodríguez,Eduardo Rodríguez Veltzé,Rodríguez Veltzé,Eduardo Rodríguez (2005-2006),Eduardo Rodríguez,Eduardo Rodríguez Veltzé,ER,ER,2005-06-09,2006-01-22 -Evo Morales,p110,Evo Morales (2006-2019),Evo Morales,Juan Evo Morales Ayma,Morales Ayma,Evo Morales (2006-2019),Evo Morales,Juan Evo Morales Ayma,EM,EM,2006-01-22,2019-11-10 -Interim military government,p111,Interim military government (2019),Military government (2019),Interim military government,Interim military government,Gobierno interino militar (2019),Gobierno interino militar (2019),Gobierno interino militar,Mil,Mil,2019-11-10,2019-11-12 -Jeanine Áñez,p112,Jeanine Áñez (2019-2020),Jeanine Áñez,Jeanine Áñez Chávez,Áñez Chávez,Jeanine Áñez (2019-2020),Jeanine Áñez,Jeanine Áñez Chávez,JÁ,JÁ,2019-11-12,2020-11-08 -Luis Arce,p113,Luis Arce (2020- ),Luis Arce,Luis Alberto Arce Catacora,Arce Catacora,Luis Arce (2020- ),Luis Arce,Luis Alberto Arce Catacora,LA,LA,2020-11-08,2025-03-20 +presidency,id_presidency,presidency_year,presidency_commonname,presidency_fullname,presidency_surnames,presidency_year_es,presidency_commonname_es,presidency_fullname_es,presidency_initials,presidency_initials_num,first_day,last_day +René Barrientos,p86,René Barrientos (1964-1969),René Barrientos,René Barrientos Ortuño,Barrientos Ortuño,René Barrientos (1964-1969),René Barrientos,René Barrientos Ortuño,RB,RB,1964-11-05,1966-08-06 +Luis Adolfo Siles Salinas,p87,Luis Adolfo Siles Salinas (1969),Luis Adolfo Siles Salinas,Luis Adolfo Siles Salinas,Siles Salinas,Luis Adolfo Siles Salinas (1969),Luis Adolfo Siles Salinas,Luis Adolfo Siles Salinas,LAS,LAS,1966-08-06,1969-04-27 +Alfredo Ovando Candía,p88,Alfredo Ovando (1969-1970),Alfredo Ovando,Alfredo Ovando Candía,Ovando Candía,Alfredo Ovando (1969-1970),Alfredo Ovando,Alfredo Ovando Candía,AO,AO,1969-04-27,1969-09-26 +Juan José Torres,p89,Juan José Torres (1970-1971),Juan José Torres,Juan José Torres González,Torres González,Juan José Torres (1970-1971),Juan José Torres,Juan José Torres González,JJT,JJT,1970-10-07,1971-08-21 +Hugo Banzer (1st),p90,Hugo Banzer (1971-1978),Hugo Banzer,Hugo Banzer Suárez,Banzer Suárez,Hugo Banzer (1971-1978),Hugo Banzer,Hugo Banzer Suárez,HB,HB 1,1971-08-22,1978-07-21 +Juan Pereda,p91,Juan Pereda (1978),Juan Pereda,Juan Pereda Asbún,Pereda Asbún,Juan Pereda (1978),Juan Pereda,Juan Pereda Asbún,JP,JP,1978-07-21,1978-11-24 +David Padilla (Chairman of the Military Junta),p92,David Padilla (1978-1979),David Padilla,David Padilla Arancibia,Padilla Arancibia,David Padilla (1978-1979),David Padilla,David Padilla Arancibia,DP,DP,1978-11-24,1979-08-08 +Wálter Guevara,p93,Walter Guevara (1979),Walter Guevara,Wálter Guevara Arze,Guevara Arze,Walter Guevara (1979),Walter Guevara,Wálter Guevara Arze,WG,WG,1979-08-08,1979-11-01 +Alberto Natusch,p94,Alberto Natusch (1979),Alberto Natusch,Alberto Natusch Busch,Natusch Busch,Alberto Natusch (1979),Alberto Natusch,Alberto Natusch Busch,AN,AN,1979-11-01,1979-11-16 +Lydia Gueiler Tejada,p95,Lidia Gueiler (1979-1980),Lidia Gueiler,Lidia Gueiler Tejada,Gueiler Tejada,Lidia Gueiler (1979-1980),Lidia Gueiler,Lidia Gueiler Tejada,LG,LG,1979-11-17,1980-07-18 +Luis García Meza Tejada (2nd),p96,Luis García Meza (1980-1981),Luis García Meza,Luis García Meza Tejada,García Meza Tejada,Luis García Meza (1980-1981),Luis García Meza,Luis García Meza Tejada,LGM,LGM,1980-07-18,1981-08-04 +Junta of Commanders of the Armed Forces 1981,p97,Junta of Commanders of the Armed Forces (1981),Military Junta (1981),Junta of Commanders of the Armed Forces of the Nation,Junta of Commanders of the Armed Forces of the Nation,Junta Militar de Comandantes de las Fuerzas Armadas (1981),Military Junta (1981),Junta Militar de Comandantes de las Fuerzas Armadas ,Junta,Junta 1981,1981-08-04,1981-09-04 +Celso Torrelio,p98,Celso Torrelio (1981-1982),Celso Torrelio,Celso Torrelio Villa,Torrelio Villa,Celso Torrelio (1981-1982),Celso Torrelio,Celso Torrelio Villa,CT,CT,1981-09-04,1982-07-19 +Junta of Commanders of the Armed Forces 1982,p99,Junta of Commanders of the Armed Forces (1982),Military Junta (1982),Junta of Commanders of the Armed Forces of the Nation,Junta of Commanders of the Armed Forces of the Nation,Junta Militar de Comandantes de las Fuerzas Armadas (1982),Military Junta (1982),Junta Militar de Comandantes de las Fuerzas Armadas ,Junta,Junta 1982,1982-07-19,1982-07-21 +Guido Vildoso,p100,Guido Vildoso (1982),Guido Vildoso,Guido Vildoso Calderón,Vildoso Calderón,Guido Vildoso (1982),Guido Vildoso,Guido Vildoso Calderón,GV,GV,1982-07-21,1982-10-10 +Hernán Siles Zuazo,p101,Hernán Siles Zuazo (1982-1985),Hernán Siles Zuazo,Hernán Siles Zuazo,Siles Zuazo,Hernán Siles Zuazo (1982-1985),Hernán Siles Zuazo,Hernán Siles Zuazo,HSZ,HSZ,1982-10-10,1985-08-06 +Víctor Paz Estenssoro,p102,Víctor Paz Estenssoro (1985-1989),Víctor Paz Estenssoro,Víctor Paz Estenssoro,Paz Estenssoro,Víctor Paz Estenssoro (1985-1989),Víctor Paz Estenssoro,Víctor Paz Estenssoro,VPE,VPE 2,1985-08-06,1989-08-06 +Jaime Paz Zamora,p103,Jaime Paz Zamora (1989-1993),Jaime Paz Zamora,Jaime Paz Zamora,Paz Zamora,Jaime Paz Zamora (1989-1993),Jaime Paz Zamora,Jaime Paz Zamora,JPZ,JPZ,1989-08-06,1993-08-06 +Gonzalo Sanchez de Lozada (1st),p104,Gonzalo Sánchez de Lozada (1993-1997),Gonzalo Sánchez de Lozada,Gonzalo Sánchez de Lozada,Sánchez de Lozada,Gonzalo Sánchez de Lozada (1993-1997),Gonzalo Sánchez de Lozada,Gonzalo Sánchez de Lozada,GSL,GSL 1,1993-08-06,1997-08-06 +Hugo Banzer (2nd),p105,Hugo Banzer (1997-2001),Hugo Banzer,Hugo Banzer Suárez,Banzer Suárez,Hugo Banzer (1997-2001),Hugo Banzer,Hugo Banzer Suárez,HB,HB 2,1997-08-06,2001-08-07 +Jorge Quiroga,p106,Jorge Quiroga (2001-2002),Jorge Quiroga,Jorge Quiroga Ramírez,Quiroga Ramírez,Jorge Quiroga (2001-2002),Jorge Quiroga,Jorge Quiroga Ramírez,JQ,JQ,2001-08-07,2002-08-06 +Gonzalo Sanchez de Lozada (2nd),p107,Gonzalo Sánchez de Lozada (2002-2003),Gonzalo Sánchez de Lozada,Gonzalo Sánchez de Lozada,Sánchez de Lozada,Gonzalo Sánchez de Lozada (2002-2003),Gonzalo Sánchez de Lozada,Gonzalo Sánchez de Lozada,GSL,GSL 2,2002-08-06,2003-10-17 +Carlos Diego Mesa Gisbert,p108,Carlos Mesa (2003-2005),Carlos Mesa,Carlos Diego Mesa Gisbert,Mesa Gisbert,Carlos Mesa (2003-2005),Carlos Mesa,Carlos Diego Mesa Gisbert,CM,CM,2003-10-17,2005-06-09 +Eduardo Rodríguez,p109,Eduardo Rodríguez (2005-2006),Eduardo Rodríguez,Eduardo Rodríguez Veltzé,Rodríguez Veltzé,Eduardo Rodríguez (2005-2006),Eduardo Rodríguez,Eduardo Rodríguez Veltzé,ER,ER,2005-06-09,2006-01-22 +Evo Morales,p110,Evo Morales (2006-2019),Evo Morales,Juan Evo Morales Ayma,Morales Ayma,Evo Morales (2006-2019),Evo Morales,Juan Evo Morales Ayma,EM,EM,2006-01-22,2019-11-10 +Interim military government,p111,Interim military government (2019),Military government (2019),Interim military government,Interim military government,Gobierno interino militar (2019),Gobierno interino militar (2019),Gobierno interino militar,Mil,Mil,2019-11-10,2019-11-12 +Jeanine Áñez,p112,Jeanine Áñez (2019-2020),Jeanine Áñez,Jeanine Áñez Chávez,Áñez Chávez,Jeanine Áñez (2019-2020),Jeanine Áñez,Jeanine Áñez Chávez,JÁ,JÁ,2019-11-12,2020-11-08 +Luis Arce,p113,Luis Arce (2020-2025),Luis Arce,Luis Alberto Arce Catacora,Arce Catacora,Luis Arce (2020-2025),Luis Arce,Luis Alberto Arce Catacora,LA,LA,2020-11-08,2025-11-08 +Rodrigo Paz,p114,Rodrigo Paz (2025- ),Rodrigo Paz,Rodrigo Paz Pereira,Paz Pereira,Rodrigo Paz (2025- ),Rodrigo Paz,Rodrigo Paz Pereira,RP,RP,2025-11-08, \ No newline at end of file diff --git a/data/lev.rda b/data/lev.rda index 77dcde0..6976105 100644 Binary files a/data/lev.rda and b/data/lev.rda differ diff --git a/data/presidency_name_table.rda b/data/presidency_name_table.rda index 8d6bea4..cbb0f81 100644 Binary files a/data/presidency_name_table.rda and b/data/presidency_name_table.rda differ diff --git a/data/president.rda b/data/president.rda index 89df703..c800ea7 100644 Binary files a/data/president.rda and b/data/president.rda differ diff --git a/man/insert_rows_by_group_vars.Rd b/man/insert_rows_by_group_vars.Rd new file mode 100644 index 0000000..cbd6168 --- /dev/null +++ b/man/insert_rows_by_group_vars.Rd @@ -0,0 +1,45 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/freq-table-hierarchical.R +\name{insert_rows_by_group_vars} +\alias{insert_rows_by_group_vars} +\title{Insert rows into a grouped table from an additional dataframe} +\usage{ +insert_rows_by_group_vars(main_df, additional_df, variable1, variable2) +} +\arguments{ +\item{main_df}{A data.frame. The primary table containing the main groups.} + +\item{additional_df}{A data.frame. Rows to be inserted into `main_df` by +matching on `variable1`.} + +\item{variable1}{Column name (unquoted) used as the grouping key (tidy-eval).} + +\item{variable2}{Column name (unquoted) indicating the second-level variable +to be inserted (tidy-eval).} +} +\value{ +A data.frame containing rows from `main_df` with rows from + `additional_df` inserted by group. Rows from `additional_df` whose + `variable1` values do not exist in `main_df` will appear as new groups. +} +\description{ +Insert rows from `additional_df` into `main_df` by matching groups defined +by `variable1`. For each unique value of `variable1` in `main_df`, if a +corresponding row exists in `additional_df` it will be appended to that +group's rows. Any `variable1` values that appear only in `additional_df` +will be appended as new groups at the end of the returned data frame. + +This function uses tidy-eval for `variable1` and `variable2` (unquoted +column names). +} +\examples{ +df_main <- data.frame(group = c("A", "A", "B"), + sub = c("x", "y", "z"), n = 1:3, stringsAsFactors = FALSE) +df_add <- data.frame(group = c("A", "C"), + sub = c("other", "other"), n_2 = c(10, 5), stringsAsFactors = FALSE) +insert_rows_by_group_vars(df_main, df_add, group, sub) + +} +\seealso{ +two_layer_frequency_table, two_layer_frequency_kable +} diff --git a/man/presidency_name_table.Rd b/man/presidency_name_table.Rd index c9b74ef..41619e2 100644 --- a/man/presidency_name_table.Rd +++ b/man/presidency_name_table.Rd @@ -8,7 +8,8 @@ A tibble with multiple columns including unqiue identifiers in `presidency` (the levels of pres_admin in English) and `presidency_id` (a unique identifier in the format "p104"). `first_day` and `last_day` - are dates indicating the term of offfice of each president. + are dates indicating the term of office of each president. The + `last_day` of the most recent presidency is set to NA. } \usage{ presidency_name_table diff --git a/man/two_layer_frequency_kable.Rd b/man/two_layer_frequency_kable.Rd new file mode 100644 index 0000000..be46879 --- /dev/null +++ b/man/two_layer_frequency_kable.Rd @@ -0,0 +1,50 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/freq-table-hierarchical.R +\name{two_layer_frequency_kable} +\alias{two_layer_frequency_kable} +\title{Two-layer frequency table (formatted kable)} +\usage{ +two_layer_frequency_kable( + dataset, + variable1, + variable2, + sort = TRUE, + threshold = 1, + unit_is_deaths = TRUE +) +} +\arguments{ +\item{dataset}{A data.frame. The input dataset.} + +\item{variable1}{Column name (unquoted) for the primary grouping variable +(tidy-eval).} + +\item{variable2}{Column name (unquoted) for the secondary grouping variable +(tidy-eval).} + +\item{sort}{Logical. If TRUE, sort groups by descending counts. Default: +TRUE.} + +\item{threshold}{Integer. Minimum count threshold for including a secondary +category. Secondary categories with counts below `threshold` will be +combined into an "Other" row. Default: 1.} + +\item{unit_is_deaths}{Logical. If TRUE, use "Deaths"/"Muertes" translation +for the secondary count label; otherwise use a generic "Numero"/"Count". +Default: TRUE.} +} +\value{ +A kableExtra kable object (HTML) styled for reporting. +} +\description{ +Create a formatted HTML kable from the two-layer frequency data. This +function calls two_layer_frequency_table() to compute the raw combined +table and then applies labeling, translation via transcats, and kableExtra +styling to produce a display-ready table. +} +\examples{ +library(dplyr) +mtcars2 <- mtcars \%>\% mutate(cyl = as.factor(cyl), gear = as.factor(gear)) +two_layer_frequency_kable(mtcars2, cyl, gear, sort = TRUE, threshold = 1) + +} diff --git a/man/two_layer_frequency_table.Rd b/man/two_layer_frequency_table.Rd new file mode 100644 index 0000000..98cc1de --- /dev/null +++ b/man/two_layer_frequency_table.Rd @@ -0,0 +1,50 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/freq-table-hierarchical.R +\name{two_layer_frequency_table} +\alias{two_layer_frequency_table} +\title{Two-layer frequency table (data)} +\usage{ +two_layer_frequency_table( + dataset, + variable1, + variable2, + sort = TRUE, + threshold = 1 +) +} +\arguments{ +\item{dataset}{A data.frame. The input dataset.} + +\item{variable1}{Column name (unquoted) for the primary grouping variable +(tidy-eval).} + +\item{variable2}{Column name (unquoted) for the secondary grouping variable +(tidy-eval).} + +\item{sort}{Logical. If TRUE, sort groups by descending counts. Default: +TRUE.} + +\item{threshold}{Integer. Minimum count threshold for including a secondary +category. Secondary categories with counts below `threshold` will be +combined into an "Other" row. Default: 1.} +} +\value{ +A data.frame (ft.combined) with columns for the primary variable, + counts (n), percentage (pct), secondary variable, and secondary counts + (n_2). +} +\description{ +Compute a two-layer frequency table (unformatted data) that contains primary +counts and percentages for `variable1` and the secondary breakdown by +`variable2`. This function returns the combined data.frame (ft.combined) +which can be further processed or passed to a kable/printing function. + +The `variable1` and `variable2` arguments use tidy-eval (unquoted column +names). +} +\examples{ +library(dplyr) +mtcars2 <- mtcars \%>\% mutate(cyl = as.factor(cyl), gear = as.factor(gear)) +two_layer_frequency_table(mtcars2, cyl, gear, sort = TRUE, threshold = 1) + +} diff --git a/tests/testthat/_snaps/add-presidency-column.md b/tests/testthat/_snaps/add-presidency-column.md index 5c7b645..7273b3d 100644 --- a/tests/testthat/_snaps/add-presidency-column.md +++ b/tests/testthat/_snaps/add-presidency-column.md @@ -83,7 +83,7 @@ 9 Evo Morales (2006-2019) Evo Morales 149 10 Gobierno interino militar (2019) Interim military government 9 11 Jeanine Áñez (2019-2020) Jeanine Áñez 26 - 12 Luis Arce (2020- ) Luis Arce 42 + 12 Luis Arce (2020-2025) Luis Arce 42 --- diff --git a/tests/testthat/_snaps/data-cleaning.md b/tests/testthat/_snaps/data-cleaning.md index cb30810..c42ca80 100644 --- a/tests/testthat/_snaps/data-cleaning.md +++ b/tests/testthat/_snaps/data-cleaning.md @@ -40,7 +40,7 @@ $ municipality : chr [1:670] "San Julián" "San Julián" "San Julián" "San Julián" ... $ province : chr [1:670] "Ñuflo de Chávez" "Ñuflo de Chávez" "Ñuflo de Chávez" "Ñuflo de Chávez" ... $ department : chr [1:670] "Santa Cruz" "Santa Cruz" "Santa Cruz" "Santa Cruz" ... - $ pres_admin : Factor w/ 13 levels "Hernán Siles Zuazo",..: 1 1 1 1 1 1 1 1 2 2 ... + $ pres_admin : Factor w/ 14 levels "Hernán Siles Zuazo",..: 1 1 1 1 1 1 1 1 2 2 ... $ protest_campaign : chr [1:670] "San Julián Colonizer Strike" "San Julián Colonizer Strike" "San Julián Colonizer Strike" "San Julián Colonizer Strike" ... $ protest_domain : Factor w/ 21 levels "Gas wars","Economic policies",..: 7 7 7 7 7 6 6 6 4 4 ... $ pol_assassination : chr [1:670] "No" "No" "No" "No" ... @@ -100,7 +100,7 @@ $ municipality : chr [1:670] "San Julián" "San Julián" "San Julián" "San Julián" ... $ province : chr [1:670] "Ñuflo de Chávez" "Ñuflo de Chávez" "Ñuflo de Chávez" "Ñuflo de Chávez" ... $ department : chr [1:670] "Santa Cruz" "Santa Cruz" "Santa Cruz" "Santa Cruz" ... - $ pres_admin : Factor w/ 13 levels "Hernán Siles Zuazo",..: 1 1 1 1 1 1 1 1 2 2 ... + $ pres_admin : Factor w/ 14 levels "Hernán Siles Zuazo",..: 1 1 1 1 1 1 1 1 2 2 ... $ protest_campaign : chr [1:670] "San Julián Colonizer Strike" "San Julián Colonizer Strike" "San Julián Colonizer Strike" "San Julián Colonizer Strike" ... $ protest_domain : chr [1:670] "Peasant" "Peasant" "Peasant" "Peasant" ... $ pol_assassination : chr [1:670] "No" "No" "No" "No" ... diff --git a/tests/testthat/_snaps/freq-table-hierarchical.md b/tests/testthat/_snaps/freq-table-hierarchical.md new file mode 100644 index 0000000..0158702 --- /dev/null +++ b/tests/testthat/_snaps/freq-table-hierarchical.md @@ -0,0 +1,92 @@ +# two_layer_frequency_table results are consistent with past runs. + + Code + two_layer_frequency_table(deaths_aug24, perp_affiliation, dec_affiliation, + sort = TRUE) + Condition + Warning in `two_layer_frequency_table()`: + The dataset contains 57 rows with NA values in perp_affiliation which will be excluded from the analysis. + Warning in `two_layer_frequency_table()`: + The dataset contains 1 rows with NA values in dec_affiliation which will be excluded from the analysis. + Output + perp_affiliation n pct dec_affiliation n_2 + Security Force 339 55.3% Cocalero 97 + Security Force 339 55.3% Civilian 83 + Security Force 339 55.3% Protester 39 + Security Force 339 55.3% Campesino 32 + Security Force 339 55.3% Miner 30 + Security Force 339 55.3% Security Force 18 + Security Force 339 55.3% Urban Movement 11 + Security Force 339 55.3% Armed Actor 7 + Security Force 339 55.3% Student 7 + Security Force 339 55.3% Teacher 6 + Security Force 339 55.3% Partisan 3 + Security Force 339 55.3% Government Officeholder 2 + Security Force 339 55.3% Factory Worker 1 + Security Force 339 55.3% Highland Indigenous 1 + Security Force 339 55.3% Narcotrafficker 1 + Security Force 339 55.3% Transport Worker 1 + Highland Indigenous 64 10.4% Highland Indigenous 61 + Highland Indigenous 64 10.4% Security Force 2 + Highland Indigenous 64 10.4% Campesino 1 + Miner 41 6.7% Miner 27 + Miner 41 6.7% Security Force 6 + Miner 41 6.7% Campesino 4 + Miner 41 6.7% Government Officeholder 1 + Miner 41 6.7% Journalist 1 + Miner 41 6.7% Lowland Indigenous 1 + Miner 41 6.7% Urban Movement 1 + Cocalero 38 6.2% Security Force 33 + Cocalero 38 6.2% Cocalero 3 + Cocalero 38 6.2% Civilian 1 + Cocalero 38 6.2% Urban Movement 1 + Partisan 31 5.1% Campesino 8 + Partisan 31 5.1% Partisan 7 + Partisan 31 5.1% Government Officeholder 4 + Partisan 31 5.1% Urban Movement 4 + Partisan 31 5.1% Teacher 3 + Partisan 31 5.1% Journalist 2 + Partisan 31 5.1% Security Force 2 + Partisan 31 5.1% Civilian 1 + Campesino 26 4.2% Campesino 8 + Campesino 26 4.2% Security Force 6 + Campesino 26 4.2% Miner 4 + Campesino 26 4.2% Civilian 2 + Campesino 26 4.2% Landowner 2 + Campesino 26 4.2% Armed Actor 1 + Campesino 26 4.2% Government Officeholder 1 + Campesino 26 4.2% Lowland Indigenous 1 + Campesino 26 4.2% Protester 1 + Urban Movement 21 3.4% Government Employee 7 + Urban Movement 21 3.4% Civilian 5 + Urban Movement 21 3.4% Campesino 3 + Urban Movement 21 3.4% Urban Movement 3 + Urban Movement 21 3.4% Cocalero 1 + Urban Movement 21 3.4% Lowland Indigenous 1 + Urban Movement 21 3.4% Security Force 1 + Landowner 17 2.8% Campesino 15 + Landowner 17 2.8% Civilian 1 + Landowner 17 2.8% Lowland Indigenous 1 + Armed Actor 7 1.1% Civilian 3 + Armed Actor 7 1.1% Campesino 1 + Armed Actor 7 1.1% Government Employee 1 + Armed Actor 7 1.1% Government Officeholder 1 + Armed Actor 7 1.1% Security Force 1 + Narcotrafficker 6 1.0% Civilian 3 + N/A 6 1.0% Lowland Indigenous 2 + N/A 6 1.0% Protester 2 + Narcotrafficker 6 1.0% Security Force 2 + N/A 6 1.0% Campesino 1 + N/A 6 1.0% Civilian 1 + Narcotrafficker 6 1.0% Government Officeholder 1 + Student 5 0.8% Student 5 + Disputed 5 0.8% Campesino 2 + Disputed 5 0.8% Civilian 2 + Disputed 5 0.8% Security Force 1 + Unknown 2 0.3% Government Officeholder 2 + Private Security 2 0.3% Protester 1 + Private Security 2 0.3% Security Force 1 + Lowland Indigenous 1 0.2% Cocalero 1 + Protester 1 0.2% Campesino 1 + Transport Worker 1 0.2% Transport Worker 1 + diff --git a/tests/testthat/test-freq-table-hierarchical.R b/tests/testthat/test-freq-table-hierarchical.R new file mode 100644 index 0000000..f600b2e --- /dev/null +++ b/tests/testthat/test-freq-table-hierarchical.R @@ -0,0 +1,30 @@ +test_that("two_layer_frequency_table results are consistent with past runs.", { + expect_snapshot(two_layer_frequency_table(deaths_aug24, + perp_affiliation, dec_affiliation, + sort=TRUE)) + mtcars2 <- mtcars %>% mutate(cyl = as.factor(cyl), gear = as.factor(gear)) + # expect_snapshot(two_layer_frequency_table(mtcars2, cyl, gear, + # sort = TRUE, threshold = 1)) +}) + +test_that("insert_rows_by_group_vars works", { + df_main <- data.frame(group = c("A", "A", "B"), + sub = c("x", "y", "z"), + n = 1:3, stringsAsFactors = FALSE) + df_add <- data.frame(group = c("A", "C"), + sub = c("other", "other"), + n = c(10, 5), stringsAsFactors = FALSE) + df_inserted <- insert_rows_by_group_vars(df_main, df_add, group, sub) + expect_equal(which(df_inserted$sub=="other"), c(3,5)) # other inserted 3rd and 5th positions + expect_equal(which(df_inserted$group=="C"), 5) # C is inserted at the end + expect_equal(df_inserted[df_inserted$group=="C",2], "other") + expect_equal(df_inserted[df_inserted$group=="C",3], 5) +}) + +# test_that("two_layer_frequency_kable results are consistent with past runs.", { +# expect_snapshot(two_layer_frequency_kable(deaths_aug24, perp_affiliation, +# dec_affiliation, sort=TRUE)) +# mtcars2 <- mtcars %>% mutate(cyl = as.factor(cyl), gear = as.factor(gear)) +# expect_snapshot(two_layer_frequency_kable(mtcars2, cyl, gear, sort = TRUE, +# threshold = 1, unit_is_deaths = FALSE)) +# })