<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Keith Karani on Medium]]></title>
        <description><![CDATA[Stories by Keith Karani on Medium]]></description>
        <link>https://medium.com/@keithkarani?source=rss-e91359615257------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gAspW86B1W4GCWvLlKJCHA.jpeg</url>
            <title>Stories by Keith Karani on Medium</title>
            <link>https://medium.com/@keithkarani?source=rss-e91359615257------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 23:36:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@keithkarani/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Scaling BasePoint into a Cloud-Integrated Monorepo]]></title>
            <link>https://medium.com/@keithkarani/scaling-basepoint-into-a-cloud-integrated-monorepo-8b8fcf947fdd?source=rss-e91359615257------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b8fcf947fdd</guid>
            <category><![CDATA[sports-analytics-software]]></category>
            <category><![CDATA[kenya]]></category>
            <category><![CDATA[rstats]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Keith Karani]]></dc:creator>
            <pubDate>Tue, 28 Apr 2026 12:14:06 GMT</pubDate>
            <atom:updated>2026-04-28T13:07:11.618Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Normalizing official game stats and establishing a source of truth in the Cloud</em></p><h4><strong>The Evolution of the Funnel</strong></h4><p>In my previous article, I detailed why reproducibility matters for high-entropy sports metrics. But a pipeline is only as strong as its surrounding infrastructure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NN9G9YTJJERkzgQwoJj3hw.jpeg" /><figcaption>Nairobi Baseball Community Series 2026 Thika Rangers VS Samurai United</figcaption></figure><p>To take Basepoint from an experiment to a “statcast of the savannah”, I have refactored the project into a modular monorepo. This ensures that statistical modeling , data ingestion , and the user interface can evolve independently.</p><h4>🏗 The New Topology: modular monolith</h4><p>I realized early on that to scale across the Nairobi Community Series and beyond, I needed a separation of concerns. I reorganized the repository into a polyglot structure where each tool does what it does best:</p><p>basepoint/<br>├── analytics/ # The Statistical Engine <br>│ ├── _targets.R # Declarative pipeline management<br>│ ├── R/ # Modular Logic (sabermetrics.R, db_utils.R)<br>│ └── data/ # Local staging for raw CSVs <br>├── api/ # (In Development) High-concurrency Ingestion Layer using Go<br>├── dashboard/ # (In Development) Angular 21 Signals-based UI<br>├── .github/workflows/ # CI/CD Pipeline validation<br>└── README.md # Documentation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B-WzsqVLlO9odrm201wIYw.jpeg" /></figure><h4>🔬 The Innings Pitched Normalization</h4><p>A critical aspect of BasePoint is the source of its data. We don’t rely on casual observations but rather our pipeline ingests<strong> </strong>official GameChanger CSV exports<strong> </strong>recorded by league officials for every game in the series. This ensures that the Source of Truth starts with regulated, high-quality inputs.</p><p>However, even official data requires normalization. In baseball, a pitcher who records one out in the first inning is listed as having pitched 0.1 innings. Standard math would treat that .1 as a tenth, but in baseball, it&#39;s a third. My workflow includes a custom normalization layer in R that uses modulo math to ensure our denominators are mathematically correct.</p><pre>library(tidyverse)<br>library(tibble)<br><br>calculate_sabermetrics &lt;- function(data) {<br>  data |&gt; <br>    as_tibble() |&gt;<br>    # Convert to numeric <br>    mutate(across(c(h, hr, ab, so, sf, bb, hbp, ip), ~as.numeric(as.character(unlist(.))))) |&gt;<br>    <br>    # Replace NA with 0 <br>    mutate(across(c(h, hr, ab, so, sf, bb, hbp, ip), ~replace_na(., 0))) |&gt;<br>    <br>    # Calculate Sabermetrics <br>    mutate(<br>      # BABIP: (H - HR) / (AB - K - HR + SF)<br>      babip = (h - hr) / (ab - so - hr + sf),<br><br>      # FIP: ((13*HR) + (3*(BB+HBP)) - (2*K)) / IP + 3.10<br>      fip = ((13 * hr) + (3 * (bb + hbp)) - (2 * so)) / ip + 3.10 <br>    ) |&gt; <br>    <br>    # Final Cleanup<br>    mutate(across(where(is.numeric), ~ if_else(is.finite(.), ., 0)))<br>}<br><br></pre><h4>🐛 The Atomic Comparison Bug</h4><p>Engineering isn’t a straight line. During my first attempt to sync my R pipeline with the Neon PostgreSQL cloud, it crashed with a cryptic error</p><blockquote><em>error: comparison (&lt;) is possible only for atomic and list types</em></blockquote><p>While building push_to_neon, I used &lt; instead of &lt;-. R attempted to mathematically compare a live <strong>S4 Database Connection </strong>to the pipeline&#39;s metadata</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1bLC1ZwKKf83OKDJ1ISUSA.png" /><figcaption>The Successful Failure: Most of the pipeline is a healthy green, but the database sync (red) highlights exactly where the atomic comparison error occurred</figcaption></figure><p>I didnot just fix the typo, I re-wrote the function to return a timestamp string upon success. This allows the {targets} engine to track the side-effect of a database upload without trying to digest complex connection objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*0JN4S4jQmMjX2ALanSYllQ.png" /><figcaption>The Verified Pipeline: After resolving the atomic comparison bug, the {targets} graph confirms a successful end-to-end sync to the cloud.</figcaption></figure><h4>📊 The Source of Truth Audit</h4><p>To close the loop, I performed a manual audit to verify that my cloud data matches my local logic.</p><p>The test case:</p><p>I queried pitching stats of one of the pitcher in the Neon SQL Console and here is the output below</p><pre>SELECT <br>    first_name, <br>    last_name, <br>    hr, <br>    bb, <br>    fip, <br>    ip_total -- This is your normalized decimal (e.g., 1.333)<br>FROM basepoint <br>WHERE first_name ILIKE &#39;%Tuju%&#39;<br>LIMIT 1;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qO1ninRVcpxX9u6C1nc-jA.png" /><figcaption>The Proof in the Cloud: A live query of the Neon PostgreSQL database confirms the precision of the Basepoint engine. Note the ip_total of 16.333 this is the result of our modulo based normalization of official GameChanger logs, ensuring that one out is treated as exactly 1/3 of an inning, preserving the integrity of Tuju Oduori’s 4.09 FIP</figcaption></figure><h4><strong>Conclusion</strong></h4><p>Building this second phase of BasePoint taught me that data engineering is 20% writing formulas and 80% ensuring the data survives the journey to the cloud. By moving from local R scripts to a cloud integrated monorepo my workflow now ensures that when a game changer stats csv is uploaded, the pipeline doesn&#39;t just read it, but audits it. From the modulo math that perfectly handles Tuju’s 16.1 innings to the atomic comparison fix that stabilized my Neon database connection, I have established a standard for our local stats and successfully bridged the gap between the red dirt of the Nairobi fields and the precision of a serverless PostgreSQL environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I025mfcX8VHrdMKZ" /><figcaption>Photo by <a href="https://unsplash.com/@joneckert?utm_source=medium&amp;utm_medium=referral">Jon Eckert</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Next Inning</h4><p>My next step is to engineer a<strong> </strong>Go-based middleware layer that transforms BasePoint from a batch-processing script into a scalable platform. This go service will act as a high-concurrency traffic controller,handling CSV file uploads from the frontend, archiving raw data for auditability, and orchestrating the R-based sabermetric engine. By moving authentication and database querying into this layer, I’m building a secure, multi-tenant system that can serve fast, JSON-ready metrics to scouts while ensuring that the heavy analytical lifting remains decoupled from the user experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b8fcf947fdd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Engineering a Reproducible Data Pipeline for High-Entropy Sports Metrics]]></title>
            <link>https://medium.com/@keithkarani/engineering-a-reproducible-data-pipeline-for-high-entropy-sports-metrics-08799491b0cd?source=rss-e91359615257------2</link>
            <guid isPermaLink="false">https://medium.com/p/08799491b0cd</guid>
            <category><![CDATA[rstats]]></category>
            <category><![CDATA[baseball]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[gda]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Keith Karani]]></dc:creator>
            <pubDate>Sat, 14 Mar 2026 11:50:25 GMT</pubDate>
            <atom:updated>2026-03-14T11:50:26.871Z</atom:updated>
            <content:encoded><![CDATA[<p>In my previous post, “Architecting a Data-Driven Meritocracy for Kenyan Baseball,” I detailed the architecture for <strong>Basepoint</strong> a platform designed to bring a true meritocracy to Kenyan baseball through data by shifting from subjective observation to objective data-backed truth. However, as any system engineer knows, a vision is only as good as the pipeline that supports it. For this phase of development, I utilized Spring 2024 data from the Thika Rangers a club I play for in the Nairobi Baseball Community Series. During ingestion, it became clear that standard, linear R scripts would not suffice for the complexity of the task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fqKzK4afqG-9wicqTz4R1g.jpeg" /><figcaption>Photo by Daudi Creates: Nairobi Baseball Community</figcaption></figure><p>The raw data, exported from the GameChanger app, as a <strong>high-entropy</strong> CSV file featuring 163 columns where the headers are locked in a Glossary row at the footer rather than the header. To transform this raw chaos into professional insights, I bypassed linear scripting in favor of a <strong>Directed Acyclic Graph (DAG)</strong> built using the targets ecosystem.</p><h3>The Orchestration Layer: _targets.R</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IqxQoPiCMJAsWJ_a" /><figcaption>Photo by <a href="https://unsplash.com/@mirzaie?utm_source=medium&amp;utm_medium=referral">Mehdi Mirzaie</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The _targets.R script is the central nervous system of Basepoint. Unlike a standard R script that executes top-to-bottom every time it is called, targets manages <strong>project state</strong> through a <strong>Directed Acyclic Graph (DAG)</strong>. To understand why it is the backbone of data engineering let’s breakdown the <strong>DAG</strong> and show how they relate with basepoint.</p><ul><li><strong>Directed:</strong> The connections (edges) between your tasks have a specific direction. Data flows from A → B. It never goes backward. In this project, the flow is: Raw CSV → Cleaned Data → Advanced Metrics → Database.</li><li><strong>Acyclic:</strong> The system “Non-cycling” ,meaning there are<strong> no loops</strong>. A task cannot point back to itself which prevents the infinite loop logic errors that frequently crash simpler systems.</li><li><strong>Graph:</strong> This is the mathematical structure composed of Nodes, our data object<strong>, </strong>and <strong>Edges, </strong>the dependencies between the nodes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*HFY6RaSk371mAA9n-H9svg.png" /><figcaption>A visualized Directed Acyclic Graph (DAG) mapping the dependency chain from raw GameChanger CSV ingestion to the final cleaned dataset. The triangle represents the process_basepoint_data function, the logical machinery that transforms raw, high-entropy data into structured, low-entropy information.</figcaption></figure><p><strong>Why is the DAG Important for Basepoint?</strong></p><p>When the tar_make() command is run, the<strong> </strong>runtime environment does not simply execute code line-by-line. Instead, the orchestrator consults the DAG to make three critical decisions:</p><p>A. Dependency Tracking (Who Needs What Check)</p><p>The DAG ensures tasks happen in the correct logical order. For example, the orchestrator “knows” it cannot calculate <strong>FIP</strong> (Fielding Independent Pitching) until the <strong>Innings Pitched</strong> variable has been extracted.</p><p>B. Smart Skipping (The Efficiency Factor)</p><p>Because the graph is directed, the system identifies which downstream parts are affected by a change. If I update a database password, the orchestrator sees that the raw_data and cleaned_data nodes are upstream and unaffected. It skips those processes entirely and only re-runs the Push to DB step, maximizing efficiency.</p><p>C. Parallel Processing</p><p>If the DAG reveals branches that do not share dependencies such as cleaning Batting Stats and Pitching Stats simultaneously the engine executes them across different processor cores in parallel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*psgzb96xRVWDRa5vgXafVw.png" /><figcaption>The Orchestration Layer: This script defines the Directed Acyclic Graph (DAG)<strong> </strong>establishing the raw_data, cleaned_data, and db_status targets, we create a clear dependency chain that ensures reproducibility.</figcaption></figure><h3>The Logic Engine: R/tidy_data.R</h3><p>The heavy lifting of the Basepoint engine occurs in tidy_data.R. Here, I utilized functional programming to reduce entropy and solve the 163 column mapping problem dynamically.</p><p>Glossary Extraction via Functional Mapping</p><p>Since the headers are stored as values in the last row of the export, I used dplyr to locate the &quot;Glossary&quot; index and purrr::map_chr() to iterate across that row. By applying stringr::str_split_fixed(), the engine programmatically crack open entries like GP=Games Played to extract the shorthand key code GP. This creates a resilient engine if the league adds new metrics, the code adapts without manual intervention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xKLUf0SbudpT8gmEcj2T1w.png" /></figure><p><strong>Batch type conversion</strong></p><p>Manual type assignment for 163 columns is a significant failure point, Instead, the engine utilizes tidyverse selection helpers:</p><p>matches(&quot;pct|percent|_p$&quot;): Uses Regular Expressions to identify every percentage-based column, stripping the &quot;%&quot; symbol and converting the value to a decimal.</p><p>as.integer(): Batches counting stats (HR, K, BB) to ensure data integrity before the load phase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2JElhJ3qeXz3v-AVwiEP9Q.png" /><figcaption>The Transformation Logic: Note the use of purrr and stringr to dynamically extract headers from the footer Glossary. This functional approach replaces fragile hard-coding with a system designed for high-volume data.</figcaption></figure><h4>Why the targets package ?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*UFEFxrhXdiCcJZ2oGq2yMg.png" /></figure><p>I implemented targets to maintain reproducibility as a non-negotiable technical requirement. Developed by Will Landau and maintained by <strong>rOpenSci</strong>, this package brings the Make philosophy from system engineering into the R environment..</p><p>The mechanical advantages:</p><p><strong>Abstraction of state:</strong> Targets caches the results of every step. Upon restarting the project, the pipeline picks up exactly where it left off, avoiding redundant computation.</p><p><strong>Cryptographic Invalidation</strong>: The package generates a unique hash for every function and data object. If a single mathematical constant is changed in a script, targets invalidates only the downstream results while keeping the upstream cleaned data intact.</p><p><strong>Bespoke Parallelism</strong>: The architecture allows for high performance computing (HPC) out of the box. As Basepoint scales to 100+ teams, the orchestrator can run the cleaning logic for each team parallel.</p><p>Technical References:</p><p>To develop this architecture, I relied on the following resoucess:</p><ul><li>The User Manual: <a href="https://books.ropensci.org/targets/"><em>The targets R Package User Manual</em></a>. This is the definitive guide by Will Landau, explaining the theory of Function-Oriented Programming (FOP) in R.</li><li>The Documentation: <a href="https://docs.ropensci.org/targets/">Official rOpenSci Documentation</a>. A deep dive into the technical API and the life cycle of a target object.</li></ul><h4>Conclusion: From Local Machine to Neon Cloud</h4><p>The final step of the pipeline is a secure push to our <strong>Neon PostgreSQL</strong> database. By automating the extraction, transformation, and loading (ETL) process I have ensured that the data driving the Basepoint Meritocracy is reproducible and scalable. Basepoint is no longer just a collection of scripts; it is a scalable data infrastructure. In the next post, I will dive into the <strong>Advanced Metrics Layer</strong>, where we use this clean foundation to calculate <strong>FIP</strong> and <strong>BABIP</strong> to separate luck from true ballplayer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08799491b0cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Architecting a Data-Driven Meritocracy for Kenyan Baseball]]></title>
            <link>https://medium.com/@keithkarani/architecting-a-data-driven-meritocracy-for-kenyan-baseball-b3a8f9f6b399?source=rss-e91359615257------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3a8f9f6b399</guid>
            <category><![CDATA[postgresql-database]]></category>
            <category><![CDATA[baseball]]></category>
            <category><![CDATA[r-programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Keith Karani]]></dc:creator>
            <pubDate>Wed, 04 Mar 2026 09:55:16 GMT</pubDate>
            <atom:updated>2026-03-04T10:44:53.293Z</atom:updated>
            <content:encoded><![CDATA[<p>The current state of sports analytics in emerging markets is often defined by a “Visibility Gap.” While high-fidelity performance data is somewhat captured at the grassroots level, it remains trapped in localized silos private CSV exports and individual team devices. To address this, I am architecting <strong>Basepoint:</strong> a data driven professional platform designed to democratize performance data through a transparent, merit-based pipeline. By migrating raw, fragmented baseball statistics into a centralized, cloud-native Source of Truth. Basepoint transforms hidden potential into verifiable, scout-ready global prospects, and giving the story of baseball in Kenya the technical backbone it deserves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kpMd5X05XMwU0_K0" /><figcaption>Photo by <a href="https://unsplash.com/@purzlbaum?utm_source=medium&amp;utm_medium=referral">Claudio Schwarz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Telling the Kenyan Baseball Story</h4><p>Diamond Digest Labs, (a startup I am building), was founded on the principle that the narrative of baseball in Africa should be told through both passion and precision. While our long-term vision spans the continent, our journey begins here in Kenya with the Nairobi baseball community. We aren’t just building an app; we are establishing a “Source of Truth” for an entire ecosystem. By taking the results from the diamond and elevating them to a global standard, we ensure that a player’s statistics are no longer just numbers on a coach’s laptop, but a verified digital CV accessible to scouts worldwide and also give the community data oriented blogs to follow their favorite teams.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6xW0T4_PNAq_UnBLvoe7_A.jpeg" /><figcaption>Nairobi Baseball Community Championship Game 2025 (Image courtesy of Daudi Creates)</figcaption></figure><h4>Architectural Foundation: The Modular Monolith</h4><p>In our initial launch <strong>(v1.0.0)</strong>, we have strategically implemented a<strong> </strong>Modular Monolithic Architecture<strong> </strong>with future plans of transition to Cloud-Native Kubernetes in (v2.0.0)<strong>. </strong>The monolith architecture provides the immediate velocity we need to iterate on our core ingestion engines. By keeping the system unified yet logically decoupled, we minimize network complexity while ensuring that a future shift to microservices is a matter of lift-and-shift rather than a total rebuild. This architecture allows our high-concurrency Go backend to work seamlessly with our R-based analytical layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*G5b-TYvYs18dWOIvG4Rq0g.png" /><figcaption>System Context Diagram - Level 0</figcaption></figure><h4>Engineering Reproducibility with R 4.5.2</h4><p>Following the <strong>Data Science Lifecycle</strong> (Import → Tidy → Transform → Model → Communicate) borrowed from by Hadley Wickham et al, in the book <em>R for Data Science (2e)</em>, we have prioritized a production-grade environment. Using R version 4.5.2 within the Positron IDE, we leverage the latest functional programming refinements including the improved native pipe operator to write clean, readable code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*AjLIRt20nkCyINZwKTCbcQ.jpeg" /></figure><p>To solve the “it works on my machine” problem, we implemented <strong>renv</strong>. This ensures that every package dependency is locked in a renv.lock file, creating a &quot;dependency time machine&quot; that allows any engineer to replicate our environment exactly. This rigor is essential when dealing with 200 plus column datasets where a single version mismatch in a cleaning library could compromise the integrity of a player&#39;s career stats.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pzZZtKLs9pJJ7Z6COTZLow.png" /></figure><pre>renv::init()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q8LBUB8J6CIeEDMxyapY8w.png" /><figcaption>The Basepoint Topology: renv.lock</figcaption></figure><h4>Navigating the Ingestion Pipeline</h4><p>The heart of our technical workflow lies in how we handle the messy reality of sports data. Our file structure is designed to separate secret management from logical processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*80OdMfb82vVFMzAzdOwHwA.png" /><figcaption>The Basepoint : Separating configuration (.env) from modularized logic (R/) ensures that the project remains scalable and secure.</figcaption></figure><p>The .env file keeps sensitive Neon PostgreSQL credentials out of version control, while our internal R scripts handle the heavy lifting as follows</p><h4><strong>db_connect.R :: The Secure Handshake</strong></h4><p>This script acts as our gateway. It doesn&#39;t just open a connection; it validates and sanitizes the environment variables, ensuring that SSL-encrypted handshakes with our cloud database are stable and quote-free.</p><h4><strong>migrate_to_neon.R :: The Democratization Bridge</strong></h4><p>This is our ETL (Extract, Transform, Load) engine. It ingests the massive csv file and uses the janitor package to normalize the columns into SQL-ready snake_case. This script is what effectively democratizes the data, moving it from a flat file into a structured relational cloud.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3yRC3FUNoXx6uJLgAOiVKg.png" /></figure><h4>Strategic Infrastructure: Why Neon PostgreSQL?</h4><p>Choosing Neon as our database provider was a deliberate choice for Diamond Digest Labs. As a serverless PostgreSQL provider, Neon offers us <strong>Database Branching</strong>. This allows the creation of a sandbox branch of our production data to test a new Scout Storytelling algorithm in R without ever risking the integrity of the live league data. Furthermore, Neon’s ability to scale to zero during off-seasons and ramp up instantly on game days ensures our infrastructure is as efficient as the players we track.</p><h4>The Journey from Plumbing to Poetry</h4><p>The data is now democratized, the environment is reproducible, and the pipeline is cloud-native. But this is only the beginning. As we move from data engineering to analytical engineering, we will begin turning these rows and columns into narratives and build on the story. See you in the next one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3a8f9f6b399" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Dugout to Data: Understanding Matrices in R Through Baseball]]></title>
            <link>https://medium.com/@keithkarani/from-dugout-to-data-understanding-matrices-in-r-through-baseball-11a2bf5df9ef?source=rss-e91359615257------2</link>
            <guid isPermaLink="false">https://medium.com/p/11a2bf5df9ef</guid>
            <category><![CDATA[rstats]]></category>
            <category><![CDATA[baseball]]></category>
            <category><![CDATA[types-of-matrices]]></category>
            <category><![CDATA[r-programming]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Keith Karani]]></dc:creator>
            <pubDate>Tue, 12 Aug 2025 12:57:30 GMT</pubDate>
            <atom:updated>2025-08-12T18:43:08.257Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g6SEyIYpsFdRzpVyjkRz7g.jpeg" /><figcaption>Image source Nairobi Baseball Community Championship series 2025</figcaption></figure><p>In our <em>From Dugout to Data</em> series, we’re stepping up to the plate again, this time to explore <strong>matrices</strong> in R. With our upcoming friendly against MMU Stommers Baseball Club on August 30th, 2025, at The Nairobi’s Field of Dreams, it’s the perfect time to dive into <strong>matrices </strong>a fundamental R concept that can help us organize and analyze game data efficiently.</p><p>Think of a matrix like a baseball score sheet: rows represent innings, columns represent teams, and each cell holds the runs scored. This structured layout makes it easy to see patterns, compare performances, and make strategic decisions. In this article, we’ll build and manipulate baseball-themed matrices in R, making the stats come alive just like plays on the diamond.</p><h4>Stepping Up to the Plate: Setting Up the Score Matrix</h4><p>Let’s start by creating a matrix to represent the runs scored by <strong>Thika Rangers</strong> and <strong>MMU Stommers</strong> in the first three innings in a hypothetical game scenario.</p><pre>runs &lt;- matrix(<br>  c(2, 1, 0,  # Thika Rangers runs in innings 1–3<br>    1, 0, 3), # MMU Stommers runs in innings 1–3<br>  nrow = 2,          # Two teams<br>  byrow = TRUE       # Fill by row (team-wise)<br>)<br></pre><p>For clear communication lets give meaningful names to the rows and columns we created in the Matrix</p><pre># Name the rows and columns<br>rownames(runs) &lt;- c(&quot;Thika Rangers&quot;, &quot;MMU Stommers&quot;)<br>colnames(runs) &lt;- c(&quot;Inning1&quot;, &quot;Inning2&quot;, &quot;Inning3&quot;)<br><br>runs<br><br>#Output<br>              Inning1 Inning2 Inning3<br>Thika Rangers        2        1        0<br>MMU Stommers         1        0        3</pre><p>nrow = 2 means we have two rows (teams), byrow = TRUE fills the matrix row by row. We’ve labeled rows as Thika Rangers and MMU Stommers, and columns as the <strong>innings</strong>. This makes our matrix readable, like a baseball box score.</p><h4>Arithmetic Operations on Matrices</h4><p>We can use matrices to quickly compare performance between teams. In our scenario let’s calculate the difference in runs per inning and observe the output we get from this operation.</p><pre># Difference in runs: Rangers - Stommers<br>run_diff &lt;- runs[1, ] - runs[2, ]<br>run_diff<br><br>#Output<br>Inning1 Inning2 Inning3 <br>      1     -1      3</pre><p>In<strong> </strong>Inning1, Rangers scored 1 more run than Stommers. In Inning 2, Rangers were outscored by 1 run hence the negative value and In the Inning3, Rangers scored 3 more runs indicating a dominant offensive as the game intensifies. This kind of quick arithmetic can show which innings we need to focus on improving.</p><h4>Extending the Scoreboard: Adding New Innings or Teams</h4><p>After the game we will definitely need to sum up the total runs scored. Let’s add a Total Runs column to sum up each team’s runs, and a New Team row for a future scrimmage opponent.</p><pre># Adding a Total column<br>total_runs &lt;- c(rowSums(runs))<br>runs &lt;- cbind(runs, Total = total_runs)<br><br># Adding a new team(wreckers) row<br>new_team &lt;- c(0, 0, 0, 0) # no runs yet<br>runs &lt;- rbind(runs, wreckers = new_team)<br><br>runs<br>#Output<br>             Inning 1 Inning 2 Inning 3 Total<br>Thika Rangers        2        1        0     3<br>MMU Stommers         1        0        3     4<br>wreckers             0        0        0     0</pre><p>rowSums(runs) calculates total runs for each team, cbind() adds that as a Total column, rbind() adds a new row for NewOpponents, wreckers, ready for when we record their stats in a future game.</p><h4>Calling the Plays: Extracting Specific Scores</h4><p>We can pull specific data from the matrix, just like checking a scorecard. Take an instance where the coach wants to know what inning did the team perform best in offense achieving more runs or what inning our opponent scored most of their runs.</p><pre>#Runs scored by Thika Rangers in inning2<br>runs[&quot;Thika Rangers&quot;, &quot;Inning2&quot;]<br><br>#All runs scored by stommers in inning 3<br>runs[&quot;MMU Stommers&quot;, 3]<br><br># All runs scored by Thika Rangers after inning 3<br>runs[&quot;Thika Rangers&quot;,]</pre><p>In this code, we start by extracting the runs scored by Thika Rangers in <em>Inning 2</em> using runs[&quot;Thika Rangers&quot;, &quot;Inning2&quot;], which uses both the row name &quot;Thika Rangers&quot; and the column name &quot;Inning2&quot; to return a single numeric value representing that inning’s score. Next, runs[&quot;MMU Stommers&quot;, 3] selects the runs scored by MMU Stommers in <em>Inning 3</em>, but here instead of the column name we use the column index 3, which corresponds to &quot;Inning3&quot;, showing how both names and numeric indices can be used for selection. Finally, runs[&quot;Thika Rangers&quot;, ] retrieves all runs scored by Thika Rangers across <em>all innings</em> by specifying the row name and leaving the column index empty, meaning we keep the entire row as a vector of their inning-by-inning scores. This combination of row and column indexing is a powerful way to pinpoint or summarize specific performance data in R’s matrices.</p><h4>Wrapping Up the Innings: What’s Next in the Series</h4><p>As you have seen, matrices in R give us a powerful way to represent and manipulate baseball game data making it easy to extract insights, project future performance, and test “what if” scenarios.</p><p>But baseball isn’t just about the numbers, it’s also about what those numbers represent. In our next installment, we’ll move from raw numeric counts to <strong>factors</strong>, a statistical data type used to store categorical variables which in our case we will be representing categorical baseball data such as player positions, pitch types, or weather conditions during a game. Think of it as shifting focus from <em>how many runs</em> to <em>what kind of plays</em> shape the game because just like a well-timed home run, knowing the categories can be a game-changer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11a2bf5df9ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning R Through Baseball: Understanding Vectors One Hit at a Time]]></title>
            <link>https://medium.com/@keithkarani/phlearning-r-through-baseball-understanding-vectors-one-hit-at-a-time-fca141a7a1dc?source=rss-e91359615257------2</link>
            <guid isPermaLink="false">https://medium.com/p/fca141a7a1dc</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[r-programming]]></category>
            <category><![CDATA[rstats]]></category>
            <category><![CDATA[nbobaseballcommunity]]></category>
            <category><![CDATA[baseball]]></category>
            <dc:creator><![CDATA[Keith Karani]]></dc:creator>
            <pubDate>Thu, 07 Aug 2025 16:02:01 GMT</pubDate>
            <atom:updated>2025-08-12T13:09:51.074Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Game 08 vs Stommerz Baseball Club: Photo credits NBO Baseball Community Series 2025" src="https://cdn-images-1.medium.com/max/1024/1*qdK0DRSnqpxrKmNYJAHgrw.jpeg" /><figcaption>Thika Rangers Baseball Club (Image source: Nairobi Baseball Community Championship series 2025)</figcaption></figure><p>I’m starting a series to teach R programming, data science &amp; eventually machine learning using baseball concepts a sport I play and umpire passionately (me in the black bandanna)in the Nairobi Baseball Community Series, representing the <strong>Thika Rangers Baseball Club</strong>. In this year’s regular season, we finished last in the league standings but majority of our games were close calls. That experience made me realize that we need more than just talent and effort. We need insight. I believe that using data can help us understand what’s really happening on the field and improve our performance. This series will document my learning journey and show how R can be used to analyze and improve baseball performance, one concept at a time.</p><p>This first article is all about <strong>vectors</strong>, which are like the batting lineup of R simple, powerful, and foundational to everything else.</p><h4>Batter Up!… what exactly is a vector in R?</h4><p>In simple terms, a vector is a collection of values. Think of it like a list of player names, jersey numbers, or the number of runs each player scored in a game all arranged in a straight line. In R, almost everything starts with a vector. If you want to do any data analysis, chances are you’ll be working with vectors a lot.</p><p>To create a vector in R, you use the c() function, which stands for &quot;combine&quot; or &quot;concatenate&quot;.</p><pre>players &lt;- c(&quot;Casper&quot;, &quot;Moses&quot;, &quot;Tuju&quot;, &quot;Karani&quot;, &quot;Steve&quot;)<br>runs_scored &lt;- c(2, 3, 2, 1, 4)</pre><p>In this code: player is a variable name storing a character vector (a vector of names) representing player names of our teams’ game day roaster while runs_scored is a numeric vectors representing the runs scored.</p><h4>All elements must be the same type</h4><p>One thing I learned early on, is that all elements in a vector have to be of the same type. That means you can’t mix numbers, text, and TRUE/FALSE values in one vector at least not without R trying to convert everything to one type. Let me show an example:</p><pre>mixed &lt;- c(1, &quot;Hit&quot;, TRUE)<br>print(mixed)<br># [1] &quot;1&quot;   &quot;Hit&quot; &quot;TRUE&quot;</pre><p>R turns everything into a character (text) because that’s the most flexible type. That can lead to weird bugs if you don’t realize it’s happening, so it’s something you have to be extra keen on.</p><h4>Vector types: The players in the team</h4><p>Vectors come in different types, just like baseball players have different positions. Here are the main types :</p><ul><li>Numeric: Regular numbers like c(1, 2.5, 3)</li><li>Integer: Whole numbers like c(1L, 2L, 3L)</li><li>Character: Text like c(&quot;Pitcher&quot;, &quot;Catcher&quot;)</li><li>Logical: is_home_team &lt;- c(TRUE, FALSE, TRUE)</li><li>Complex and Raw stores complex numbers which include a real and an imaginary part (e.g., 2 + 3i). Imagine you’re modeling a pitch’s movement: the horizontal (x-axis) movement is the real part, and the vertical (y-axis) movement is the imaginary part. A complex number 3 + 2i might represent a fastball with 3 units of horizontal movement and 2 units of rise. This gives you a compact way of describing a two-dimensional pitch path.</li></ul><h4>What can you do with vectors?</h4><p>This is where vectors start to feel really powerful. You can do all sorts of operations on them and R handles it in a smart way.</p><ol><li>Accessing individual elements</li></ol><pre>players[1]<br>#Casper<br><br>runs_scored[2]<br>#3</pre><p>2. Slicing: Getting multiple elements</p><pre>players[2:4]<br># &quot;Moses&quot; &quot;Tuju&quot; &quot;Karani&quot;</pre><p>3. Filtering using conditions</p><pre>runs_scored[runs_scored &gt; 2]<br># 3 4</pre><p>4. Doing arthmetic operation</p><pre>runs_scored &lt;- c(2, 3, 2, 1, 4)<br>runs_scored * 2<br># [1] 4 6 4 2 8</pre><p>5. Getting summary statistics</p><pre>sum(runs_scored)   # total runs<br>mean(runs_scored)  # average runs<br>max(runs_scored)   # highest runs</pre><p>6. Find the top performer based on runs scored in that game</p><pre>players[which.max(runs_scored)]<br># &quot;Steve&quot;</pre><h4>Game scenario: game summary</h4><p>Below I have player names and the number of runs each scored in game 8 of the regular season match</p><pre>players &lt;- c(&quot;Casper&quot;, &quot;Moses&quot;, &quot;Tuju&quot;, &quot;Karani&quot;, &quot;Steve&quot;)<br>runs_scored &lt;- c(2, 3, 2, 1, 4)</pre><p>Using this data I can calculate the following:</p><ul><li>Find the total team runs: <em>sum(runs)</em></li><li>Calculate the average runs per player: <em>mean(runs_scored)</em></li><li>See who scored no runs: players: <em>players[runs_scored == 0]</em></li><li>Find the MVP based on runs scored: <em>players[which.max(runs_scored)]</em></li></ul><h4>Inning pointers</h4><p>Vectors are everywhere in R and if you get comfortable with them, everything else gets easier. It’s important to pay attention to types. Mixing types inside a vector can mess things up and it’s worth noting that R is really good at handling operations on entire vectors.</p><h4>What’s next?</h4><p>As we’ve seen, vectors are the lead-off hitters of R setting the pace, laying the foundation, and always getting on base when it comes to data manipulation. Whether you’re dealing with game scores, player stats, or league standings, understanding how to create and manipulate vectors is a crucial skill.</p><p>In our next innings, we’ll dive deeper into how vectors interact with data frames and how to use them in analyzing real baseball data from the Thika Rangers Baseball club game stats.</p><p>And with that, I’ll step behind the plate and make the call:</p><h4><strong>That’s the ball game! From Dugout to Data</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iw9djbtFODnYq98SKhnjxQ.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fca141a7a1dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>