---
title: "RIFanalysis Workflow: Multi-Group Comparison"
subtitle: "Datasets without a `Type` Variable (Z2 and Z3)"
author: "RIFanalysis package authors"
fontsize: 13pt
header-includes:
  - \usepackage{amssymb}
  - \usepackage{latexsym}
  - \usepackage{amsmath,amsthm}
  - \usepackage{bm}
date: '`r format(Sys.time(), "%d/%m/%y")`' # ver https://bookdown.org/yihui/rmarkdown-cookbook/update-date.html
lang: "en-US"
output:
  rmarkdown::html_vignette:
    toc: true
    toc_depth: 4
vignette: >
  %\VignetteIndexEntry{RIFanalysis Workflow: Multi-Group Comparison}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
editor_options:
  markdown:
    wrap: 72
---

```{r setup, include=FALSE}
#knitr::opts_chunk$\alphaet(echo = FALSE)
knitr::opts_chunk$set(message = FALSE, eval=FALSE)
knitr::opts_chunk$set(fig.align = "center") #solo para html
knitr::opts_chunk$set(fig.width = 8)
knitr::opts_chunk$set(dpi = 1200)
```


<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<!-- Separador -->


# Introduction

This vignette demonstrates the standard workflow for **comparing two or more groups** when the input datasets do **not** contain a **`Type`** variable. Other vignettes describe the workflow for single-group analyses and for multi-group comparisons with a **`Type`** variable.

Starting from two or more datasets containing observed frequencies, the workflow prepares each dataset independently, fits discrete power-law models, computes the Relative Importance Factor (RIF), and generates publication-ready comparative tables and visualizations.

Most users will only need the high-level workflow functions described in this vignette. The **Advanced usage** section introduces lower-level functions for users who require additional customization.


<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<!-- Separador -->

# Methodological foundation

The methods implemented in the **`RIFanalysis`** package are based on the following publication:

[Llinas, B., Padilla, J., Llinas, H., Frydenlund, E., & Palacio, K. (2026). *Modeling Rank Distribution and the Relative Importance Factor Index in Discrete Power-Law Models: Application to Social Resilience Using the Scopus Database*. Mathematics, 14(6), 966.](https://www.mdpi.com/2227-7390/14/6/966).


<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<!-- Separador -->

# Workflow overview

The complete analysis is organized into three main stages. First, each input dataset is standardized independently using **`rif_prepare()`**. Next, **`rif_workflow_z2()`** fits the discrete power-law models, computes the RIF measures for each group, and constructs the comparative RIF results. Finally, **`rif_workflow_z3()`** generates publication-ready visualizations from the combined results.

```text
             Group 1 dataset       Group 2 dataset
                    │                     │
                    ▼                     ▼
             rif_prepare()         rif_prepare()
                    │                     │
                    └──────────┬──────────┘
                               ▼
                      rif_workflow_z2()
                               │
                ┌──────────────┼──────────────┐
                ▼              ▼              ▼
          Power-law fits   RIF comparison   Excel files
                               │
                               ▼
                      rif_workflow_z3()
                               │
                ┌──────────────┼──────────────┐
                ▼              ▼              ▼
         RIF matrices   RIF networks   Publication-ready figures
```


The workflow consists of the following steps:

1. Define user-specific objects and input parameters.

2. Import and prepare the datasets.

3. Fit discrete power-law models for each group.

4. Compute group-specific and comparative RIF measures.

5. Generate comparative tables and graphical outputs.

6. Export results to Excel and image files.

<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<!-- Separador -->


# Load the package

```{r, echo=TRUE, warning=FALSE, message=FALSE}
library(RIFanalysis)
```



<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<!-- Separador -->

# Input datasets


The comparative analysis begins by loading the reproducible example datasets
included with RIFanalysis. Each dataset should contain variables identifying
the factors (or topics), their short labels, and their observed frequencies.
The example below uses two datasets. They should represent comparable groups,
since they will be analyzed jointly by **`rif_workflow_z2()`**.


```{r}
data("data_no_type", package = "RIFanalysis")
data_gr1 <- data_no_type$data_gr1
data_gr2 <- data_no_type$data_gr2
```


<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<!-- Separador -->

# User-defined objects

Before running the workflow, define the objects that specify variable names, group labels, plot labels, output directories, and other user-specific settings. Most of these values can be left unchanged, but they may be customized for different applications.

Because the datasets used in this vignette do not contain **`Group`** or **`Type`** variables, the objects **`gr_value_name1`**, **`gr_value_name2`**, **`var_type_value_name1`**, and **`var_type_value_name2`** do not refer to columns in the original datasets. Instead, they define labels assigned during the data preparation step through the **`group_value`** and **`type_value`** arguments of **`rif_prepare()`**.



```{r}
# Review required variable names (ALWAYS verify them in the dataset)
fact_lbl_prefix1        <- "gr1T"                # Choose according to your needs (gr=group, T=topic, C=concept, F=factor, I=index, etc.)
var_factor_name1        <- "factor"              # Long/original FACTOR variable
var_factor_small1       <- "factor_small"        # Short FACTOR variable
var_factor_label_small1 <- "factor_label_small"  # FACTOR_label_small variable
var_count_name1         <- "count"               # COUNT variable

fact_lbl_prefix2        <- "gr2T"                # Choose according to your needs (gr=group, T=topic, C=concept, F=factor, I=index, etc.)
var_factor_name2        <- "factor"              # Long/original FACTOR variable
var_factor_small2       <- "factor_small"        # Short FACTOR variable
var_factor_label_small2 <- "factor_label_small"  # FACTOR_label_small variable
var_count_name2         <- "count"               # COUNT variable

# Assign a common Type label to all observations because the datasets do not contain a Type variable.
var_type_value_name1  <- "corpus_type"  # Option B (abstract, index, etc.)
var_type_value_name2  <- "corpus_type"  # Option B (abstract, index, etc.)

# Assign labels identifying the groups to be compared.
gr_value_name1  <- "gr1_NAME"  # Change (Colombia, Greece, Blue Economy, etc.)
gr_value_name2  <- "gr2_NAME"  # Change (Colombia, Greece, Blue Economy, etc.)
#prefix_name <- paste0(gr_name, "_")

#________________________________________________________________________
#

# If desired, change axis title  for RIF matrices (Topic, Concept, Factor, etc.) and labels.
# IN rif_workflow_z3, SEE plot_matrix.R FUNCTION:

# Axis title:
x_title_name  <-  "s: CHANGE_NAME at rank s" # default: Concept
y_title_name  <-  "r: CHANGE_NAME at rank r" # default: Concept
# Axis labels:
factor_r_label_col_name <- "Factor_label" # default: factor_r_label_col = NULL
factor_s_label_col_name <- "Factor_label" # default: factor_s_label_col = NULL

#________________________________________________________________________
#
# Customize titles for power-law plots generated by rif_workflow_z2() and plot_zipf().
# Title default is "Observed and theoretical Zipf distributions..."
title_plotzipf_gr1_c2 <- "GROUPNAME1" # Change if desired
title_plotzipf_gr2_c2 <- "GROUPNAME2" # Change if desired

x_title_plotzipf_c2   <- "Position"  # Change if desired (default="Rank")
y_title_plotzipf_c2   <- "Frequency" # Change if desired (default="Count")

#________________________________________________________________________
#

# Change custom file names (if desired)
file_prefix_no_title     <- "zipf_notitle"
file_prefix_yes_title_c1 <- "zipf_yestitle_c1"
file_prefix_yes_title_c2 <- "zipf_yestitle_c2"

# Change output directories (if desired)
output_dir_personal   <- file.path(tempdir(), "Z0_personal")
output_dir_comparison <- file.path(tempdir(), "Z2_RIF_comparison")
output_dir_visual     <- file.path(tempdir(), "Z3_RIF_visual")
```




<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<!-- Separador -->

# Descriptive Zipf analysis

Each dataset must be prepared independently before running the comparative workflow. The **`rif_prepare()`** function validates the input data, assigns Zipf ranks, and creates the standardized tables required by **`rif_workflow_z2()`**.

The resulting objects, **`rif_data1`** and **`rif_data2`**, represent the prepared datasets for Groups 1 and 2, respectively.



```{r}
rif_data1 <- rif_prepare(data= data_gr1,
    factor_col = var_factor_name1,
    count_col = var_count_name1,
    factor_small_col = var_factor_small1,
    group_col = NULL,
    type_col = NULL,
    group_value = gr_value_name1,
    type_value = var_type_value_name1,
    prefix = fact_lbl_prefix1,
    factor_small_label_style = "inline")

rif_data1
names(rif_data1)
```


<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<!-- Separador -->



```{r}
rif_data2 <- rif_prepare(data= data_gr2,
    factor_col = var_factor_name2,
    count_col = var_count_name2,
    factor_small_col = var_factor_small2,
    group_col = NULL,
    type_col = NULL,
    group_value = gr_value_name2,
    type_value = var_type_value_name2,
    prefix = fact_lbl_prefix2,
    factor_small_label_style = "inline")

rif_data2
names(rif_data2)
```


<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<!-- Separador -->


# Z2: Multi-Group Power-Law Estimation and RIF Comparison

The comparative workflow is executed with **`rif_workflow_z2()`**. This function fits the discrete power-law model separately for each group, computes the corresponding RIF measures, constructs the comparative RIF results, generates diagnostic plots, and exports the resulting tables and figures.


```{r}
z2 <- rif_workflow_z2(
    rif_data1 = rif_data1,
    rif_data2 = rif_data2,
    alpha_zipf = 1,
    no_of_sims = 1000,
    threads = 8,
    seed = 123,
    bootstrap_engine = "manual",
    output_dir = output_dir_comparison,
    plot_formats = c("png", "pdf")
    )
```


The workflow returns a single object containing both the individual analyses for each group and the combined comparative results. The table below summarizes its most important components.

| Component                      | Description                                                            |
| :----------------------------- | :--------------------------------------------------------------------- |
| `input1`, `input2`             | Original input objects for Groups 1 and 2.                             |
| `data1`, `data2`               | Prepared datasets returned by `rif_prepare()`.                         |
| `zipf1`, `zipf2`               | Descriptive Zipf tables for each group.                                |
| `analysis1`, `analysis2`       | Power-law estimation and intermediate analysis results for each group. |
| `rif_results1`, `rif_results2` | Complete group-specific RIF results.                                   |
| `rif_comparison`               | Combined object containing the comparative RIF results.                |
| `plots`                        | Group-specific plots generated by the workflow.                        |
| `files`                        | Paths to exported Excel files and graphical outputs.                   |

The following commands illustrate how to access the principal components.

```{r, eval=FALSE}
z2$input1
z2$input2

z2$data1
z2$data2

z2$zipf1
z2$zipf2

z2$analysis1
z2$analysis2

z2$rif_results1
z2$rif_results2

z2$rif_comparison
z2$plots
z2$files
```




<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<!-- Separador -->

# Z3: RIF Visualization

The **`rif_workflow_z3()`** function generates publication-ready comparative visualizations from **`z2$rif_comparison`**. In this example, the combined results are used to create RIF matrices and networks representing relationships across the analyzed groups.


```{r}
rif_workflow_z3(
  x = z2$rif_comparison,
  scope = "combined",
  plot_types = c("matrix", "network"),
  plot_formats = c("png", "pdf"),
  save_plots = TRUE,
  plot_dpi = 600,
  #plot_types = "matrix",
  output_dir = output_dir_visual,

  #SEE plot_matrix.R FUNCTION:
  matrix_args = list(
    #factor_r_label_col = factor_r_label_col_name,
    factor_s_label_col = factor_s_label_col_name,
    x_title = x_title_name,
    y_title = y_title_name
    )
)
```



<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<!-- Separador -->


# Advanced usage

Most low-level functions used in this workflow are identical to those described in **Vignette 1: Single-Group Analysis**. For this reason, they are not repeated here.

This section presents only the objects and functions that are specific to the multi-group comparison workflow implemented in **`rif_workflow_z2()`**.


```{r}
z2$plots$group1
z2$plots$group2

z2$files$group1
z2$files$group2

z2$files$plots
z2$files$excel
```
