---
title: "RIFanalysis Workflow: Single-Group Analysis" 
subtitle: "Datasets without a `Type` Variable (Z1 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: Single-Group Analysis}
  %\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 datasets containing a **single group** and **no `Type` variable**. Other vignettes describe the workflows for multi-group comparisons and for datasets containing a **`Type`** variable.

Starting from a table of observed frequencies, the workflow prepares the data, fits a discrete power-law model, computes the Relative Importance Factor (RIF), and generates publication-ready 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 as a sequence of three main stages. First, the input dataset is standardized using **`rif_prepare()`**. Next, **`rif_workflow_z1()`** performs the power-law estimation and computes the RIF measures. Finally, **`rif_workflow_z3()`** generates publication-ready visualizations from the computed RIF results.

```text
                 Input dataset
                       │
                       ▼
                rif_prepare()
                       │
                       ▼
             rif_workflow_z1()
                       │
          ┌────────────┼────────────┐
          ▼            ▼            ▼
     Excel files   Zipf plots   RIF results
                                     │
                                     ▼
                           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 dataset.

3. Fit discrete power-law models.

4. Compute Relative Importance Factor (RIF) measures.

5. Generate 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 dataset

The analysis begins by importing the input dataset. At a minimum, the dataset should contain variables identifying the factors (or topics), their short labels, and their observed frequencies.

```{r}
data_gr1 <- read.csv("0_data_gr1.csv")
```



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

# User-defined objects

Before running the workflow, define the objects that specify variable names, 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 this vignette is designed for datasets containing a **single group** and **no `Type` variable**, the objects **`gr_value_name`** and **`var_type_value_name`** do **not** refer to columns in the input dataset. Instead, they define labels that are assigned to all observations 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_prefix        <- "grT"                # Choose according to your needs (gr=group, T=topic, C=concept, F=factor,     
                                               # I=index, etc.)
var_factor_name        <- "factor"             # Long/original FACTOR variable
var_factor_small       <- "factor_small"       # Short FACTOR variable
var_factor_label_small <- "factor_label_small" # FACTOR_label_small variable
var_count_name         <- "count"              # COUNT variable

# Assign a label to the analysis because the dataset does not contain a Type variable.
var_type_value_name  <- "corpus_type"  # Change (abstract, index, etc.)

# Assign a label identifying the single analysis group.
gr_value_name  <- "GROUPNAME1"  # 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

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_default   <- file.path(tempdir(), "Z1_RIF_basic")
output_dir_visual    <- file.path(tempdir(), "Z3_RIF_visual")
```




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

# Descriptive Zipf analysis

The first step is to prepare the dataset for the RIF workflow. The **`rif_prepare()`** function validates the input data, assigns Zipf ranks, and creates the standardized table required by the remaining functions. The resulting object (**`rif_data1`**) serves as the input for all subsequent workflow functions.

```{r}
rif_data1 <- rif_prepare(data= data_gr1, 
    factor_col = var_factor_name,
    count_col = var_count_name ,
    factor_small_col = var_factor_small,
    group_col = NULL,
    type_col = NULL,
    group_value = gr_value_name,
    type_value = var_type_value_name,
    prefix = fact_lbl_prefix,
    factor_small_label_style = "inline")
```

Inspect the resulting object if desired.

```{r}
rif_data1
names(rif_data1)
```




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

# Z1: Power-law Estimation and RIF Computation

The main workflow is executed with **`rif_workflow_z1()`**. This function fits the discrete power-law model, computes all RIF measures, generates diagnostic plots, and optionally exports the results to Excel and image files.

```{r}
z1 <- rif_workflow_z1(
    rif_data= rif_data1,
    alpha_zipf = 1,
    no_of_sims = 1000,
    threads = 8,
    seed = 123,
    bootstrap_engine = "poweRlaw",
    output_dir = output_dir_default,
    excel_file = NULL,
    zipf_excel_file = NULL,
    save_excel = TRUE,
    save_plots = TRUE,
    plot_formats = c("png", "pdf"),
    plot_format = NULL,
    plot_dir = NULL,
    plot_width = 8,
    plot_height = 6,
    plot_dpi = 300
)
```

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

The workflow returns a single object containing all intermediate and final results. The table below summarizes its most important components.

| Component | Description |
|:----------|:------------|
| `data` | Prepared input dataset returned by `rif_prepare()`. |
| `zipf` | Descriptive Zipf table with observed and derived variables. |
| `analysis` | Power-law estimation results and intermediate analysis objects. |
| `rif_results` | Complete RIF results used for visualization and export. |
| `plots` | Collection of plots generated during the workflow. |
| `files` | Paths to exported Excel files and graphical outputs. |

The following commands illustrate how to access each component.

```{r, eval=FALSE}
z1$data
z1$zipf
z1$analysis
z1$rif_results
z1$plots
z1$files
```



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


# Z3: RIF Visualization 

The **`rif_workflow_z3()`** function generates publication-ready visualizations, including RIF matrices, networks, and other graphical summaries derived from the computed RIF results.

```{r}
rif_workflow_z3(
  x = z1$rif_results,
  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

The following examples illustrate how individual functions can be used independently of the main workflow to customize plots, export files, or inspect intermediate objects.

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


### `plot_zipf`

The **`plot_zipf()`** function creates Zipf distribution plots with optional customization of titles, axis labels, and factor labels. 


```{r}
# Default title
plt_zipf_withTitle_c1 <- plot_zipf(tbl_zipf, 
                               label_col = var_factor_label_small)
plt_zipf_withTitle_c1
```


The plot title and axis labels can be customized as follows.

```{r}
#Custom title 
plt_zipf_withTitle_c2 <- plot_zipf(tbl_zipf, 
                               label_col = var_factor_label_small,
                               title = title_plotzipf_gr1_c2, 
                               x_title = x_title_plotzipf_c2, 
                               y_title = y_title_plotzipf_c2)
plt_zipf_withTitle_c2
```



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

 To suppress the plot title, simply provide an empty string.

```{r}
#No title
plt_zipf_noTitle <- plot_zipf(tbl_zipf, 
                               label_col = var_factor_label_small, 
                               title = "")
plt_zipf_noTitle
```

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

### `export_rif_plots` (custom)

After creating a plot, use **`export_rif_plots()`** to save it in one or more formats such as PNG or PDF.

```{r}
export_rif_plots(
  plots = plt_zipf_withTitle_c1,
  output_dir = output_dir_personal,
  file_prefix = file_prefix_yes_title_c1,
  formats = c("png", "pdf")
  )
```


```{r}
export_rif_plots(
  plots = plt_zipf_withTitle_c2,
  output_dir = output_dir_personal,
  file_prefix = file_prefix_yes_title_c2,
  formats = c("png", "pdf")
  )
```


```{r}
export_rif_plots(
  plots = plt_zipf_noTitle,
  file_prefix = file_prefix_no_title,
  output_dir = output_dir_personal,
  formats = c("png", "pdf")
  )
```


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

### `rif_zipf`

If only the descriptive Zipf table is required, use **`rif_zipf()`**. This function extends the prepared dataset with additional Zipf-related variables.


```{r}
tbl_zipf <- rif_zipf(rif_data1)
tbl_zipf
names(tbl_zipf)
```




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

### `rif_fit_powerlaw`

The **`rif_fit_powerlaw()`** function performs only the discrete power-law estimation and returns the corresponding model object, without computing the complete RIF results.


```{r}
plreg <- rif_fit_powerlaw(
    data= rif_data1,
    count_col = "count",
    group_col = "group",
    group = NULL,
    type_col = "type",
    type = NULL,
    no_of_sims = 1000,
    threads = 8,
    seed = 123,
    bootstrap_engine = c("poweRlaw")
)

names(plreg$df_KS_boot)
```


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


### `rif_analysis`

The **`rif_analysis()`** function extends the power-law estimation by creating the analysis object required for the computation of RIF measures.


```{r}
rif_an <- rif_analysis(data = rif_data1, threads = 8)
rif_an$tables$ks_boot
```

Compare: 

```{r}
names(rif_an$tables$ks_boot)
names(plreg$df_KS_boot)
```


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


### `z1$zipf` 

The **`zipf`** component returned by the workflow is equivalent to the object generated by **`rif_zipf()`**.


```{r}
z1_zipf <- z1$zipf
z1_zipf
```

Compare: 

```{r}
class(z1_zipf)
class(tbl_zipf)
```

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


### `z1$rif_results`

The **`rif_results`** component contains all estimated RIF measures and serves as the primary input for visualization and export functions.


```{r}
rif_result_z1 <- z1$rif_results
rif_result_z1
class(rif_result_z1)
```





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

### `rif_compute_results`

When the analysis is performed manually, **`rif_compute_results()`** combines the intermediate results into the complete RIF results object.

```{r}
rif_result_an <- rif_compute_results(rif_an)
class(rif_result_an)
rif_result_an
```


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


### Exporting and importing Excel files

The package also provides functions for exporting and importing complete RIF analyses in Excel format.


```{r}
# Export
export_rif_excel(
  rif_result_an,
  file.path(tempdir(), "Z0_personal", "rif_result_an.xlsx")
)
```


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


```{r, eval=FALSE}
# Import
rif_result_excel <- import_rif_excel("Workflow_results/Z1_RIF_basic/NOM_RIF_3sheets.xlsx") #Change NOM
rif_result_excel
class(rif_result_excel)
```


