Sesión 11: Transformando datos en información con R y Rstudio

Sesión 11: Transformando datos en información con R y Rstudio

Introduction to Class 11: Percentages and Data Structuring in R

Overview of the Class

  • The class focuses on percentages, restructuring data, and creating informative tables using R and R Studio. Emphasis is placed on organizing tables aesthetically for better readability.
  • Previous lessons covered frequency tables, statistical measures like median and variance, which will aid in analyzing current data sets.

Data Context

  • Today's dataset consists of 620 sales across six branches, five cities, and twelve products. This builds upon previous classes that dealt with data cleaning and organization.
  • Students are instructed to start a new R Markdown file linked to their Excel dataset for effective analysis.

Working with Libraries in R

Essential Libraries

  • Key libraries include Tidyverse for data transformation, Janitor for frequency tables, Read XL for reading Excel files, Lubridate for date handling, and Scales for formatting numbers.
  • The Scales library allows customization of number formats (e.g., changing decimal points based on regional preferences).

Installation Instructions

Installing Required Libraries

  • Students are guided on how to install necessary libraries by writing commands within the script. Comments are indicated using the numeral symbol (#).
  • An alternative installation method involves using a vector format where multiple library names can be listed together.

Code Execution Guidance

Running Code Simultaneously

  • The instructor plans to share code snippets via Classroom so students can execute them concurrently during the lesson.

Preparing Data Environment

Cleaning Up Workspace

  • Students are reminded to clean their environment before executing new code to avoid confusion from previous variables or datasets.

Merging Datasets

Concatenating Sheets

  • A reminder is given about ensuring all relevant files are stored in one folder so that R can access them correctly when merging sheets from Excel.

Teaching Methodology

Step-by-Step Approach

  • The instructor emphasizes a gradual teaching approach by explaining each line of code rather than executing everything at once to prevent information overload.

Calculating Percentages

Understanding Proportions

  • To calculate percentages, divide individual values by the total count; this yields results between 0 and 1 initially before converting into percentage form.

Practical Application

Using Sales Data

  • After preparing the dataset named "ventas completas," students will perform calculations focusing on specific channels such as online sales versus physical store sales.

Utilizing Mutate Function

Creating New Variables

  • When calculating proportions or percentages within datasets using mutate, it’s crucial not to overwrite original variables but instead create new ones for clarity.

Executing Percentage Calculations

Steps in Calculation

  • By applying mutate alongside division operations (n/sum(n)), students learn how to derive proportions effectively from their datasets.

Formatting Results

Presenting Percentages

  • Different methods of presenting calculated percentages include rounding off decimals or appending percentage signs directly through functions provided by libraries like Scales.

Transitioning from Specific to General Concepts

Introduction to Data Presentation

  • The discussion begins with a focus on moving from specific examples to broader concepts, emphasizing the importance of simplicity in initial presentations.
  • It is noted that numerical data should be formatted correctly, such as rounding decimals or presenting whole numbers for clarity.
  • R provides matrix-like indications of data structure, highlighting the number of rows and columns present in the dataset.

Accumulated Percentage Analysis

  • The concept of accumulated percentages is introduced, particularly in relation to sales analysis using Pareto principles.
  • An example illustrates how cumulative percentages are calculated by adding individual product sales percentages sequentially.
  • Visual representation through graphs can effectively show linear growth patterns based on accumulated data.

Practical Applications of Sales Data

  • Understanding total inventory sold versus individual product sales helps in assessing overall performance and stock management.
  • Participants are encouraged to explore more about Pareto analysis while working with grouped product sales data.

Structuring Data for Analysis

Organizing Sales Information

  • Emphasis is placed on accurately naming variables as they appear in tables to avoid errors during analysis.
  • Sorting data from highest to lowest values is crucial for effective accumulation and subsequent analysis.

Calculating Percentages

  • A reminder about the structure needed when calculating percentages: having a numerator and denominator defined clearly.
  • The use of cumulative sum functions (cumsum) allows for tracking running totals within datasets.

Advanced Grouping Techniques

Grouped Percentage Calculations

  • Discussion shifts towards handling multiple variables simultaneously when calculating percentages, stressing the need for identifying a clear 100% baseline.
  • An example involving city-based sales demonstrates how grouping affects percentage calculations differently than overall totals.

Importance of Grouping Logic

  • Without proper grouping, percentage calculations may yield misleading results by aggregating across unrelated categories instead of focusing on specific groups.

Utilizing Libraries for Efficiency

Streamlining Code with Libraries

  • Introduction to libraries that simplify coding processes by allowing users to perform complex operations succinctly.
  • Functions like adorn help add totals and percentages directly into frequency tables without extensive coding efforts.

Formatting Outputs Effectively

  • Proper formatting options allow users to specify decimal places when displaying percentage outputs, enhancing readability and precision.

Transforming Data Formats

Wide vs. Long Format Data Structures

  • Explanation of wide versus long formats highlights their utility depending on the type of analysis being conducted; long format often aids in cleaning and organizing data better.

Converting Between Formats

  • Examples illustrate how transforming between formats can facilitate easier visualization and reporting while maintaining analytical integrity.

Transforming Data Formats in R

Converting Long Format to Wide Format

  • The process begins with the need to calculate quarterly totals by category, transitioning from a long format to a wide format for better data representation.
  • The pivot_wider function is introduced, which allows conversion of long data into wide format by specifying new column names derived from existing columns.
  • In this transformation, the values that populate the cells are defined; in this case, they will be sourced from the 'total' column.
  • After executing the code, it is noted that the wide format now contains four rows and four columns compared to 16 observations in three variables in the long format.
  • The integration of beverage sales across different quarters is highlighted, showcasing how totals are presented clearly without character variables.

Handling Missing Values

  • A pause is taken for questions regarding pivot operations; emphasis on understanding before proceeding further is encouraged.
  • Comments within the code clarify its purpose and functionality; textual descriptions accompany slides for additional context on coding scenarios.
  • When encountering missing combinations in data, these can be replaced with zeros or other specified values during initial data cleaning processes.
  • An example illustrates converting age entries into numerical formats for easier analysis while maintaining clarity in data representation.
  • Observations about transforming long-format data into a more structured wide-format table are reiterated.

Reversing Data Transformation: From Wide Back to Long

  • The discussion shifts towards reverting back to long format using pivot_longer, emphasizing how information should be organized aesthetically when exporting to Excel or similar formats.
  • Columns designated for conversion into rows are identified; this process aims at creating a visually appealing output suitable for reporting purposes.
  • New column titles and value assignments are established as part of restructuring the dataset effectively while ensuring clarity and coherence in naming conventions.
  • Excluding specific categories during transformation can be achieved through simple syntax adjustments within the code structure.
  • A comparison between two chunks of code execution highlights differences based on included versus excluded categories.

Importance of Code Efficiency

  • Emphasis on utilizing only necessary code segments promotes efficiency and reduces redundancy within scripts used for analysis.
  • Combining previous steps leads to comprehensive coding practices where multiple variables can be counted simultaneously using functions like count.

Calculating Percentages and Totals

  • Establishing total counts by channel alongside category becomes crucial; percentages calculated after summation ensure accuracy in reporting metrics.
  • Consistency in naming conventions throughout coding prevents errors related to variable recognition during execution phases.
  • It’s critical first to compute averages before summing totals across rows or columns—this maintains integrity within calculations performed.

Implementing Functions in Data Analysis

Introduction to Function Creation

  • The speaker discusses the importance of creating a complete sales table and establishing functions for data analysis.
  • Emphasizes the need to avoid repetitive coding by defining structures beforehand, which streamlines the process.

Visualizing Data Tables

  • Demonstrates how to save and visualize two tables: one for complete sales and another for survey recommendations.
  • Highlights key components of the sales table, including payment methods, sales figures, and percentages.

Enhancing Table Functionality

  • Discusses the utility of predefined formats to maintain consistency across multiple tables without redundant coding.
  • Mentions that varying table colors based on information type is valid but may increase code complexity.

Interactive Features with Data Tables

  • Introduces the DT library for creating interactive data tables where users can select variables like sale ID and date.
  • Explains how users can interactively filter records and adjust displayed information dynamically.

Advanced Table Options

  • Describes additional features such as adding filters similar to Excel, enhancing user experience with dynamic data manipulation.
  • Shows options for incorporating buttons into tables for easier copying or downloading of information in specific formats.

Final Thoughts on Table Design

  • Concludes with an overview of improving table aesthetics through margins, fonts, and background colors.
  • Encourages students to engage in practical exercises related to complete sales data while referencing shared resources.

Upcoming Topics and Questions

  • Mentions planned discussions on interactive tables and graphs in future classes while addressing student inquiries about code examples.
  • Reminds students about pagination features that enhance usability in large datasets during upcoming sessions.

Turn any video into a summary like this

YouTube links, meetings, lectures. With transcripts, search, and chat.