lares: Lean Analytics and Robust Exploration Sidekick

website·Indexed 30 days ago

https://laresbernardo.github.io/lares/index.html

An R package providing a diverse set of utilities for data science, including H2O AutoML integration, text mining (RAKE, sentiment breakdown, wordclouds), financial portfolio reporting, AES-256-CBC file encryption, and specialized tools for solving Sudoku and mazes.

Tokens
75.5K
Snippets
437
Records
615
Agent score
73%

What's inside lares

  1. Overview of the lares R library

    The lares library is an R package developed to provide tools for better and faster analytics, visualization, data mining, and machine learning tasks. It serves as a sidekick for Lean Analytics and Robust Exploration.
  2. Overview of lares R package capabilities

    lares is an R package designed to automate and accelerate analytics and machine learning workflows. Its core capabilities include:

    • Machine Learning: AutoML pipelines, model training, and evaluation.
    • Data Processing: Data cleaning and smart one-hot encoding (ohse()).
    • Exploratory Data Analysis (EDA): Data summarization and visualization (freqs(), distr(), corr_var(), corr_cross()).
    • Reporting & Visualization: Plotting for classification/regression models and MMM reports.
    • Integrations: API scrapers, Meta Marketing API (fb_*), and OpenAI API (gpt_*).
    • Specialized Analysis: Time series, portfolio analysis, and NLP/text analytics.
    • Security: Credentials and secrets management, including encrypted file I/O (read_encrypted(), write_encrypted()).
  3. Overview of lares R package capabilities

    lares is an R package designed to automate and accelerate analytics and machine learning workflows. It provides specialized function families for:

    • Machine Learning: AutoML pipelines, model training, and evaluation.
    • Data Cleaning & Processing: Data preparation for modeling.
    • Exploratory Data Analysis (EDA): Data visualization and summarization.
    • Reporting: Generating reports for Marketing Mix Models (MMM) and ML models.
    • Visualization: Plotting for regression, classification, and timelines.
    • API & Scraping: Data collection utilities.
    • Time Series & Portfolio Analysis: Financial and temporal data tools.
    • Secrets Management: Secure handling of credentials in pipelines.
    • NLP: Text analytics and processing.
  4. Perform automated K-Means clustering with clusterKmeans

    The clusterKmeans function automates the process of grouping data into distinct non-overlapping subgroups. It handles preprocessing steps such as one-hot encoding for categorical variables and data normalization. Note that K-Means assumes spherical cluster shapes and may not perform well with elliptical clusters. Scaling/standardizing data is recommended.
    # Example: Run K-Means with a specific number of clusters (k=3)
    clusters <- clusterKmeans(df, k = 3)
    
    # Access the resulting dataframe with the 'cluster' column
    clustered_df <- clusters$df
    
    # Plot cross-correlations for each cluster
    plot(clusters$correlations)
  5. Write R objects directly to an encrypted file

    Use write_encrypted() to write a list, vector, or any JSON-able object directly into an encrypted file. If no key is provided, the function generates one and returns it.
    my_secrets <- list(
      api_key = "some_secret_api_key_123",
      username = "data_analyst",
      server = "production.server.com"
    )
    
    # Write to file and capture the generated key
    raw_key <- write_encrypted(data = my_secrets, output_file = "secrets.enc", quiet = FALSE)
  6. Generate a Cumulative Gain Plot using mplot_gain

    The mplot_gain function creates a cumulative gains chart (or 'gains plot'). This visualization helps determine the expected target capture rate when selecting the best X deciles of a population based on model scores. It shows the percentage of total positive cases 'gained' relative to the percentage of the total population targeted.
    # Example for a Binomial Model
    mplot_gain(
      tag = dfr$class2$tag, 
      score = dfr$class2$scores,
      caption = "Titanic Survived Model",
      target = "TRUE"
    )
  7. Example: Balance Titanic dataset by survival status

    These examples demonstrate how to use balance_data to achieve a 1:1 ratio or a specific custom ratio using the Titanic dataset (dft).
    # Load Titanic dataset
    data(dft)
    
    # Balance to a 1:1 ratio (rate = 1)
    # This will automatically reduce the most frequent label
    df_balanced <- balance_data(dft, Survived, rate = 1)
    
    # Balance to a 0.5 ratio, specifically reducing the "TRUE" label
    df_custom <- balance_data(dft, .data$Survived, rate = 0.5, target = "TRUE")
  8. Transform categorical data using ohse (One Hot Smart Encoding)

    The ohse function automatically transforms a dataframe by converting categorical columns into numerical ones using one-hot encoding. It can also generate additional features from date/time columns and include holiday data.
    ohse(
      df,
      redundant = FALSE,
      drop = TRUE,
      ignore = NULL,
      dates = FALSE,
      holidays = FALSE,
      country = "Venezuela",
      currency_pair = NA,
      trim = 0,
      limit = 10,
      variance = 0.9,
      other_label = "OTHER",
      sep = "_",
      quiet = FALSE,
      ...
    )
  9. Use try_require for dependency management

    Use try_require to manage library dependencies in R scripts. Set stop = TRUE for mandatory dependencies that should halt the script, and stop = FALSE for optional packages where a warning is sufficient to notify the user.
    # Mandatory dependency
    try_require("ggplot2", stop = TRUE)
    
    # Optional dependency
    try_require("shiny", stop = FALSE)
  10. Example: Fetch daily campaign performance metrics

    This example shows how to retrieve daily results for all campaigns in an account, specifying custom performance fields like reach, frequency, and spend without any breakdowns.
    token <- "YOURTOKEN"
    which <- "act_20846447"
    
    insights_adset <- fb_insights(
      token, which,
      time_increment = "1",
      report_level = "campaign",
      fields = c(
        "adset_id",
        "reach",
        "frequency",
        "spend",
        "cpm",
        "objective",
        "optimization_goal"
      )
    )
  11. Format ggplot2 axis labels with comma, percent, dollar, or abbreviated scales

    The lares package provides shorthand functions to quickly format axis text in ggplot2. These functions act as wrappers around continuous scales to apply specific formatting styles:

    • scale_x_comma() / scale_y_comma(): Formats numbers with commas.
    • scale_x_percent() / scale_y_percent(): Formats numbers as percentages.
    • scale_x_dollar() / scale_y_dollar(): Formats numbers as currency (dollars).
    • scale_x_abbr() / scale_y_abbr(): Formats numbers using abbreviations.
    library(ggplot2)
    # Example using dollar and abbreviated scales
    ggplot(df, aes(x = sales, y = volume)) +
      geom_point() +
      scale_x_dollar() +
      scale_y_abbr()
    
    # Example using comma and percent scales with standard ggplot2 scale arguments (e.g., limits)
    ggplot(df, aes(x = listings, y = log(inventory))) +
      geom_point() +
      scale_x_comma() +
      scale_y_percent(limits = c(0, 3))
  12. Encrypt a file using AES-256-CBC

    Use encrypt_file() to encrypt a file. The process pads the data, generates a random Initialization Vector (IV), and prepends the IV to the encrypted data in the output file. The encryption key must be a raw vector of 32 bytes (256 bits).
    # Generate a random 32-byte key
    raw_key <- openssl::rand_bytes(32)
    
    # Encrypt the file
    encrypt_file(input_file = "secrets.txt", output_file = "secrets.enc", key = raw_key)