---
title: "RIFanalysis Workflow: Multi-Group Comparison by Type"
subtitle: "Datasets with 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 by Type}
  %\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 **include a `Type` variable**. Other vignettes describe the workflows for single-group analyses and for multi-group comparisons without a **`Type`** variable.

Starting from datasets containing observed frequencies for multiple groups and types, the workflow prepares each dataset, fits discrete power-law models for each group–type combination, 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()`**, preserving the categories defined by its **`Type`** variable. Next, **`rif_workflow_z2()`** fits the discrete power-law models and computes the RIF measures for the group–type combinations, producing the comparative RIF results. Finally, **`rif_workflow_z3()`** generates publication-ready visualizations from the combined results.

```text
            Group 1 dataset           Group 2 dataset
           (multiple types)          (multiple types)
               ┌────────┐               ┌────────┐
               │ Type A │               │ Type A │
               │ Type B │               │ Type B │
               │ Type C │               │ Type C │
               └────┬───┘               └────┬───┘                    
                    │                        │
                    ▼                        ▼
              rif_prepare()            rif_prepare()
                    │                        │
                    └────────────┬───────────┘
                                 ▼
                        rif_workflow_z2()
                                 │
                      Group × Type comparisons
                                 │
                                 ▼
                         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 and type.

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


```{r}
# library(readr)
data_gr1 <- read.csv("0_data_gr1.csv")
data_gr2 <- read.csv("0_data_gr2.csv")
```




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

# User-defined objects 

Because the datasets used in this vignette do not contain a **`Group`** variable, the objects **`gr_value_name1`** and **`gr_value_name2`** define group labels that are assigned during data preparation through the **`group_value`** argument of **`rif_prepare()`**.

In contrast, the datasets already contain a **`Type`** variable. Therefore, **`var_type_name1`** and **`var_type_name2`** identify the corresponding columns in the original datasets through the **`type_col`** argument.


```{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        <- "factor1"              # Long/original FACTOR variable
var_factor_small1       <- "factor_small1"        # Short FACTOR variable
var_factor_label_small1 <- "factor_label_small1"  # FACTOR_label_small variable
var_count_name1         <- "count1"               # 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        <- "factor2"              # Long/original FACTOR variable
var_factor_small2       <- "factor_small2"        # Short FACTOR variable
var_factor_label_small2 <- "factor_label_small2"  # FACTOR_label_small variable
var_count_name2         <- "count2"               # COUNT variable

# Identify the Type column available in each input dataset
var_type_name1  <- "type1"  # Change 
var_type_name2  <- "type2"  # Change

# Assign labels identifying the groups to be compared because the datasets do not contain a Group variable
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

#________________________________________________________________________
#

# Change titles for power-law plots (used in rif__workflow_z1 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 = var_type_name1,
    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 = var_type_name2,
    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: Group-by-Type Power-Law Estimation and RIF Comparison

The comparative workflow is executed with **`rif_workflow_z2()`**. This function fits discrete power-law models for the group–type combinations represented in the prepared datasets, 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 = "poweRlaw",
    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 preserving the `Type` categories. |
| `zipf1`, `zipf2` | Descriptive Zipf tables by group and type. |
| `analysis1`, `analysis2` | Power-law estimation results for the group–type combinations. |
| `rif_results1`, `rif_results2` | Group-specific RIF results stratified by type. |
| `rif_comparison` | Combined object containing the group-by-type comparative RIF results. |
| `plots` | Group- and type-specific plots generated by the workflow. |
| `files` | Paths to exported Excel files and graphical outputs. |

 The objects returned by **`rif_workflow_z2()`** have the same overall structure as those described in **Vignette 2: Multi-Group Comparison**. When a **`Type`** variable is present, the corresponding tables, analyses, plots, and exported files are internally organized by type.
 
 The following commands illustrate how to access the principal components.


```{r, eval=FALSE}
# Original input objects
z2$input1
z2$input2

# Input object classes
z2$input_class1
z2$input_class2

# Prepared datasets
z2$data1
z2$data2

# Descriptive Zipf tables
z2$zipf1
z2$zipf2

# Power-law analysis (`plreg`) objects
z2$analysis1
z2$analysis2

# RIF result objects
z2$rif_results1
z2$rif_results2

# Comparative RIF results
z2$rif_comparison

# Generated plots
z2$plots

# Exported files and directories
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"),
  formats = c("png", "pdf"),
  #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** and **Vignette 2: Multi-Group Comparison**. For this reason, they are not repeated here.

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


```{r}
# Individual group plots
z2$plots$group1
z2$plots$group2

# File information for Group 1
z2$files$group1

# File information for Group 2
z2$files$group2

# All generated plot files
z2$files$plots

# Comparative Excel file
z2$files$excel


```


