<?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 Kam on Medium]]></title>
        <description><![CDATA[Stories by Kam on Medium]]></description>
        <link>https://medium.com/@kambytes?source=rss-d5f74c9b9959------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*D_NrJi6fdZA65fxh0GWluQ@2x.jpeg</url>
            <title>Stories by Kam on Medium</title>
            <link>https://medium.com/@kambytes?source=rss-d5f74c9b9959------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 22:09:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kambytes/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[Understanding and Using Code Chunk Options in R]]></title>
            <link>https://medium.com/@kambytes/understanding-and-using-code-chunk-options-in-r-17589fc2166a?source=rss-d5f74c9b9959------2</link>
            <guid isPermaLink="false">https://medium.com/p/17589fc2166a</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[rstudio]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[r-markdown]]></category>
            <dc:creator><![CDATA[Kam]]></dc:creator>
            <pubDate>Sun, 15 Mar 2026 15:53:17 GMT</pubDate>
            <atom:updated>2026-03-16T03:53:08.900Z</atom:updated>
            <content:encoded><![CDATA[<p>I’d like to start by wishing my readers a very happy new year! Apologies for the long hiatus, but I’m back and excited to continue sharing my learnings!</p><p>When I first started using R Markdown, I treated code chunks as simple containers for running code. The chunk options felt confusing and unnecessary. But once I started generating PDF reports and reproducible analyses, I realised how useful they actually are as a feature of R Markdown.</p><p><strong>In this post I’m going to explain code chunk options from the beginning</strong>: understanding what code chunks are in R, how and why they’re useful, how they work behind the scenes, and how we can use them to our advantage in practice.</p><h3><strong>What are code chunks in R?</strong></h3><p><strong>Code chunks</strong> are blocks (or “<strong>cells</strong>”) where you write and run code inside an R Markdown document. If you’re familiar with <strong>Jupyter Notebooks</strong>, the idea is very similar. Both environments allow you to mix written text with executable code organised into cells or chunks.</p><p>When working with a .Rmd (<strong>R Markdown</strong>) or <strong>R Notebook</strong> file in <strong>RStudio</strong>, you can insert these code chunks and type your R code inside them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jLzaJy6ZRDl6MyFkZ009UQ.png" /><figcaption>This is an image of a code chunk. I’ve named this chunk ‘code_chunk1’.</figcaption></figure><h4>What are these backticks ``` in my R Markdown file?</h4><p>Before moving forward, I want to briefly touch on the <strong>triple</strong> <strong>backticks </strong>you see in R Markdown. These are part of the <strong>syntax used to define code chunks</strong>. When you view your R Markdown or R Notebook file in <strong>Source mode</strong>, you will see three backticks at the beginning and end of each code chunk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*TYFNee1bkIGBQnY5vSgjkA.png" /><figcaption>R Markdown (.Rmd) file in Source mode shows the backticks starting and ending each code chunk.</figcaption></figure><ul><li>{r} specifies that the code inside the chunk should be run using <strong>R.</strong></li><li>This first line inside {} is called the <strong>chunk</strong> <strong>header.</strong></li><li>Anything written between the opening and closing back ticks is treated as <strong>executable code.</strong></li></ul><p>When a chunk is <strong>run</strong>, the results appear in the <strong>Console</strong> below. When the document is <strong>knitted</strong>, the code is executed and the results appear in the final rendered document (PDF/HMTL/Word).</p><h3>What are chunk options? Why even use them?</h3><p><strong>Code chunk options</strong> are like <strong>settings</strong> that control how a code chunk behaves when it is executed or when the document is knitted. These options, written in the <strong>chunk header</strong>, allow you to customise things such as:</p><ul><li>whether the code itself is shown</li><li>whether the output is displayed</li><li>whether warnings or messages appear</li><li>whether the code runs at all</li></ul><p>There are many more options available, and they allow the user to decide <strong>what they want to see and how they want the knitted document to look</strong>.</p><blockquote>Have you ever been in a situation where you’re running a large block of code in R (or even a cell in Jupyter notebooks) and you’re annoyed by how much scrolling you need to do just to find the final result? Or by the large amount of output with unnecessary or extra results you don’t actually need?</blockquote><p>R Markdown provides solutions for this, and <strong>code chunk options are one of the main tools that make this possible when creating clean and readable reports</strong>.</p><h3>How do they work?</h3><p>Code chunk options are written in the <strong>chunk header</strong>, which appears at the top of every code chunk. When you insert a new chunk, you will see something like this:</p><pre>```{r}<br>```</pre><p>The r tells R Markdown that the code inside this chunk should be executed using <strong>R</strong>. Inside the <strong>chunk</strong> <strong>header</strong> is where we add our options.</p><p>The first element in the header specifies the <strong>language engine</strong>. Although R Markdown is commonly used for R code, it is not limited to R. Through R Markdown you can also run other languages such as <strong>Python, SQL, and Bash</strong>, which makes it a flexible environment for data science workflows.</p><p>For example, you could also run:</p><pre>```{python}<br>import pandas as pd<br><br>data = [10, 20, 30]<br>print(sum(data))<br>```<br><br>```{sql}<br>SELECT *<br>FROM mtcars<br>LIMIT 5;<br>```<br><br>```{bash}<br>echo &quot;Hello from the terminal&quot;<br>ls<br>```</pre><p>This allows you to combine different languages within the same R Markdown file while keeping everything in one workflow.</p><h4>Behind the scenes of chunk options</h4><p>Understanding what happens behind the scenes made it much easier for me to grasp how code chunk options work within R Markdown.</p><p>Code chunk options are part of the <a href="https://yihui.org/knitr/"><strong>knitr</strong></a> package created by Yihui Xie. When a document is <strong>knitted</strong>, knitr processes each code chunk <strong>one by one (by R’s Just-In-Time compilation)</strong>. For each chunk it:</p><ol><li>reads the <strong>chunk header</strong></li><li>applies any <strong>options specified there</strong></li><li>runs the code if it is set to be evaluated</li><li>inserts the resulting output into the knitted document</li></ol><p>So the options we write in the header essentially act as <strong>instructions for knitr</strong>, telling it how that particular chunk should be evaluated and how its results should appear in the knitted document.</p><h4>Writing chunk options</h4><p>Chunk options are written in the format of <strong>tag = value pairs</strong>. The first argument after the language (r) can optionally be the <strong>name of the code chunk.</strong></p><blockquote>Naming chunks can be helpful for organising your document and identifying chunks more easily.</blockquote><p>After that, multiple options can be added and are <strong>separated using commas</strong>. Most chunk options already have <strong>default values. </strong>For many options, the default behaviour is TRUE, so you don’t always need to explicitly specify them. For example:</p><pre>```{r code_chunk1a, echo=FALSE, warning=FALSE}<br>```</pre><p>Here we are telling R Markdown:</p><ul><li>echo = FALSE → do not show the code in the output</li><li>warning = FALSE → suppress warning messages</li></ul><p>This allows you to control exactly what appears during execution and within the knitted document.</p><h3>Let’s use them for our benefit</h3><p>Below are some useful chunk options that I’ve personally found helpful when writing R Markdown documents. I’ve included screnshots of example code and of how the output looks when the chunk is executed.</p><h4>1. eval</h4><p><strong>Evaluate</strong> controls whether the code inside the chunk should be executed when you knit your R Markdown file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*arIeF4E6JlYjsVqxu8Te6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*Fv-iHAwaiCB-Ks3Xn3jfMg.png" /><figcaption>Using ‘eval = FALSE&#39; shows the executed output in the .Rmd but prevents it from being executed when the document is knitted.</figcaption></figure><p>Useful when you want to <strong>show code without actually running it.</strong> For example, demonstrating installation commands.</p><h4>2. warning</h4><p><strong>Warning</strong> controls whether warning messages appear in the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*YVqQwgLI9GonVLCirzGZtQ.png" /><figcaption>The first chunk uses ‘warning = TRUE’ and displays the warning message once chunk is executed. In the second chunk, the ‘warning = FALSE’ option suppresses warning message.</figcaption></figure><p>Helpful when warnings are not relevant to the reader and would just clutter the knitted document.</p><h4>3. include</h4><p><strong>Include</strong> is my favourite/most used option and controls whether the chunk appears in the knitted document at all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*K3oWtdBPdAQNTVgqOLCrow.png" /><figcaption>Using ‘include = FALSE’ runs the code but hides both the code and the output from the knitted document.</figcaption></figure><p>The code will still run, but <strong>neither the code nor the output will appear in the knitted document</strong>. I often used for <strong>setup code chunks</strong> in the beginning where you load libraries or prepare data.</p><h4><strong>4. echo</strong></h4><p><strong>Echo</strong> is a commonly used option which hides your code while still displaying output in your knitted document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*fpclJIKIcEOJAWiPxMGRYA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*dG--9o8w3JDJ5eLdOYvSqA.png" /><figcaption>Image on the left is in the .Rmd file and the right shows the result of ‘echo = FALSE’ in the knitted document. R code is missing above the displayed output.</figcaption></figure><p>This is often used while wanting to display graphs in the knitted document but not source code to create a seamless report.</p><h4>5. fig.width and fig.height</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*qM4EtCwmQ6pW4U-KVec5wA.png" /><figcaption>The ‘fig.width’ and &#39;fig.height&#39; options control the size of figures generated in a code chunk. With thecurrent settings, the graph looks very squished.</figcaption></figure><h4>Other useful options</h4><p>There are many other options available. You can explore the full list of options in the creator <a href="https://yihui.org/knitr/">YiHui’s knitr documentation</a> which I found quite helpful and easy to read and understand.</p><h4>Beginner’s tip</h4><blockquote>The chunk header <strong>must be written on a single line</strong>. If you break the line incorrectly, the chunk may not run as expected.</blockquote><blockquote>However, there is an alternative syntax using #| which allows chunk options to be written on multiple lines. If you’d like to explore this approach, I suggest you read the <a href="https://yihui.org/knitr/options/#chunk-options">knitr documentation: Chunk Options</a>.</blockquote><h4>Setting global chunk options</h4><p>At this point you might be thinking: <em>“Typing all these options for every single chunk seems tedious…” </em>And you’d be right. Fortunately, R Markdown provides a way to define <a href="https://rmarkdown.rstudio.com/lesson-3.html"><strong>global chunk options</strong></a>. This is usually done in a setup chunk near the top of your .Rmd file.</p><pre>```{r setup}<br>knitr::opts_chunk$set(echo=TRUE, warning=FALSE, message=FALSE)<br>```<br># Options passed to knitr::opts_chunk$set() define the<br># default behaviour for all code chunks in the document.</pre><p>The example code above tells knitr to treat these options as <strong>default settings for every chunk in the .Rmd file</strong>. If you want to change the behaviour for a specific chunk later, you can simply override the option in that chunk’s header.</p><p>This keeps your document cleaner and avoids repeating the same options everywhere.</p><p>I hope you learnt something new and found this post useful! Feel free to leave a comment if you have any questions or thoughts. I’ll see you in the next one 😄.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17589fc2166a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Convert a Shapefile to GeoJSON Using Python and GeoPandas Library]]></title>
            <link>https://medium.com/@kambytes/convert-a-shapefile-to-geojson-using-python-and-geopandas-library-b20347c5ea92?source=rss-d5f74c9b9959------2</link>
            <guid isPermaLink="false">https://medium.com/p/b20347c5ea92</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[geospatial]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Kam]]></dc:creator>
            <pubDate>Sun, 13 Jul 2025 08:30:28 GMT</pubDate>
            <atom:updated>2025-07-13T08:30:28.469Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A Leaflet.js map displaying coastal data, sourced from a GeoJSON file, with styled geographic features overlaid." src="https://cdn-images-1.medium.com/max/1024/1*LGWqd93SD61VEEI-myXTfA.png" /><figcaption>GeoJSON data overlayed on an interactive Leaflet.js map</figcaption></figure><p>This June, I kicked off a full-stack web development project focused on visualising and predicting coastal erosion along Western Australia’s coastline. It uses publicly available geospatial datasets and overlays them onto an interactive map built with <strong>Leaflet.js</strong>.</p><p>One of the first challenges I ran into was that <strong>one of my datasets came as a shapefile</strong>, and I needed it in <strong>GeoJSON </strong>format to use with Leaflet.js.</p><p>At the time, I had little experience with GIS (Geographic Information Systems) and wanted to automate this process using code, not GUI-based tools like QGIS or ArcGIS. That’s when I came across the Python library <strong>GeoPandas</strong>.</p><p>In this post, I’ll walk through:</p><ul><li>What shapefiles and GeoJSON are,</li><li>How I used Python to convert one into the other,</li><li>Common mistakes I made (and how to avoid them),</li><li>And some helpful tips for working with GIS data in code.</li></ul><h3><strong>What is a Shapefile?</strong></h3><figure><img alt="A file explorer window showing the contents of a shapefile: .shp, .shx, .dbf, and other files grouped in the same directory." src="https://cdn-images-1.medium.com/max/982/1*GXHh7k9Qu6gkMkCjEUekOw.png" /><figcaption>The folder structure of a typical shapefile</figcaption></figure><p>A <a href="https://www.esri.com/content/dam/esrisites/sitecore-archive/Files/Pdfs/library/whitepapers/pdfs/shapefile.pdf"><strong>shapefile</strong></a> is a format used to store geospatial vector data. Things like <strong>points, lines, and polygons</strong> that represent features on a map. Despite the name, <em>a “shapefile” isn’t just a single file</em>. It’s actually a group of files that all work together to describe both the <strong>geometry</strong> (the shapes) and the <strong>data</strong> (the attributes or info about each shape).</p><p>At minimum, a shapefile has <strong>three files</strong>:</p><ul><li><strong>.shp</strong> — this stores the actual shapes (like lines for coastlines or points for locations)</li><li><strong>.shx</strong> — an index file that helps link everything together</li><li><strong>.dbf</strong> — this stores the data table, kind of like a spreadsheet with info about each shape</li></ul><p><strong>There can be more files too, depending on the dataset, but those three are the core ones.</strong></p><p>When I first looked at a shapefile, I was honestly confused. I thought I had downloaded the wrong thing because it came as a bunch of weird file extensions. But now I know, that’s just how shapefiles work!</p><h3>What is GeoJSON?</h3><p><strong>GeoJSON</strong> is a file format based on <strong>JSON</strong> (JavaScript Object Notation) that’s used to represent geographic data. (If you’ve done any kind of web development or worked with APIs, you’ve probably come across JSON before). It’s just a way of easily storing structured data in a text format.</p><p>The difference is that GeoJSON adds extra fields to describe spatial stuff; such as <strong>coordinate points</strong>, <strong>lines</strong>, and<strong> polygons</strong>, as well as properties that give information about each feature.</p><p>You’ll usually see something like this structure at the beginning:</p><pre>{<br>  &quot;type&quot;: &quot;FeatureCollection&quot;,<br>  &quot;features&quot;: [<br>    {<br>      &quot;type&quot;: &quot;Feature&quot;,<br>      &quot;geometry&quot;: {<br>        &quot;type&quot;: &quot;Point&quot;,<br>        &quot;coordinates&quot;: [115.8575, -31.9505]<br>      },<br>      &quot;properties&quot;: {<br>        &quot;name&quot;: &quot;Perth&quot;,<br>        &quot;category&quot;: &quot;City&quot;<br>      }<br>    }<br>  ]<br>}</pre><h4>Now, how do I even understand what my GeoJSON says?!</h4><p>I too was initially confused with understanding what was going on in my GeoJSON file. The best way to figure out the sort of data you are dealing with is to inspect it in your code editor.</p><ol><li>Open it in a <strong>code editor</strong> (like VS Code or even your browser).</li><li>Look at the <strong>“geometry”</strong> field to see what kind of shapes it includes: <strong>Point</strong>, <strong>Linestring</strong>, <strong>Polygon </strong>etc.</li><li>Look at the <strong>“properties”</strong> field to see what attributes each feature has.</li></ol><p>For more information about GeoJSON and specific geometry types and all, I found this <a href="https://doc.arcgis.com/en/arcgis-online/reference/geojson.htm">documentation article</a> helpful.</p><h3><strong>The Library: GeoPandas</strong></h3><p><strong>Geopandas</strong> is a python library which allows for easy working with geospatial information. To find out more about this beautiful library’s capabilities, check out the <a href="https://geopandas.org/en/stable/">Geopandas documentation</a>.</p><p>You can install Geopandas by running this on your terminal:</p><pre>pip install geopandas</pre><p>If you hit any installation issues, I recommend checking out the official <a href="https://geopandas.org/en/stable/getting_started/install.html">installation guide</a>.</p><h3><strong>Step-by-Step: Converting Shapefile to GeoJSON</strong></h3><p>Here’s the full step-by-step with the exact code I used and some tips along the way.</p><h4><strong>1. Set up your Python script</strong></h4><p>In your Python file, start by importing the Geopandas libaray:</p><pre>import geopandas as gpd</pre><p>It’s a common convention to import GeoPandas as <strong>gpd</strong>, just like how we import Pandas as <strong>pd</strong>. But this is completely up to you.</p><h4><strong>2. Read your shapefile</strong></h4><p>Use the <strong>read_file()</strong> method to load the shapefile.</p><pre>import geopandas as gpd<br><br><br>gdf = gpd.read_file(&quot;data/erosion_hotspots.shp&quot;)</pre><p>Here, <strong>gdf </strong>stands for <strong>GeoDataFrame</strong>. It’s just a variable which we will use to store the spatial/geometric data.</p><ul><li>The string passed inside the read_file() method is the file path to your .shp file.</li></ul><h4>3. (Optional) 🧭 Convert the coordinate reference system (CRS)</h4><p>A <strong>CRS</strong> (Coordinate Reference System) is basically what the name itself says; a coordinate system that defines the location of a point on Earth.</p><p>If that sounds a bit technical, don’t worry. You don’t need to fully understand CRS to follow along. Just know that different datasets might use different systems, and sometimes we need to convert them to make sure everything lines up properly.</p><p>For web mapping tools like <strong>Leaflet.js</strong>, it’s best to use <strong>EPSG:4326</strong>, which means regular latitude and longitude coordinates (also called WGS84).</p><p>To check your shapefile’s CRS after loading it with GeoPandas, run:</p><pre>print(gdf.crs)</pre><p>If it prints <strong>EPSG:4326</strong>, you’re all set; no need to do anything. But if it’s something else (like <strong>EPSG:7844</strong>, which uses meters and is commonly used in Australia), convert it by:</p><pre>import geopandas as gpd<br><br>gdf = gpd.read_file(&quot;data/erosion_hotspots.shp&quot;)<br>gdf = gdf.to_crs(epsg=4326)</pre><p>You only need to do this if your shapefile uses a different system and you’re planning to use the output with web maps like Leaflet.js. For more detail, I found this guide helpful <a href="https://runebook.dev/en/articles/leaflet/index/crs-code">CRS guide on Runebook.dev</a>.</p><h4>4. Export to GeoJSON</h4><p>Now write the data to a <strong>.geojson file</strong> using the <strong>to_file()</strong> method:</p><pre>import geopandas as gpd<br><br>gdf = gpd.read_file(&quot;data/erosion_hotspots.shp&quot;)<br>gdf = gdf.to_crs(epsg=4326)<br>gdf.to_file(&quot;data/erosion_hotspots.geojson&quot;, driver=&#39;GeoJSON&#39;, index=False)</pre><ul><li><strong>driver=‘GeoJSON’ </strong>specifies the output file type.</li><li><strong>index=False</strong> makes sure an index column is not added to your file.</li></ul><h4>5. (Optional) Add a print statement to confirm success</h4><p>Depending on the size of your shapfile, sometimes the conversion may take a while. I find it helpful to know when the conversion is completed by adding a print statement at the end.</p><pre>import geopandas as gpd<br><br>gdf = gpd.read_file(&quot;data/erosion_hotspots.shp&quot;)<br>gdf = gdf.to_crs(epsg=4326)<br>gdf.to_file(&quot;data/erosion_hotspots.geojson&quot;, driver=&#39;GeoJSON&#39;, index=False)<br><br>print(&quot;The shapefile has been converted into GEOJSON file format.&quot;)</pre><h3>Things I Learned Along the Way (So You Don’t Make the Same Mistakes)</h3><h4>1. You must specify the .shp file type, not just the folder</h4><p>At first, I tried passing in the folder that had all the shapefile components, but it didn’t work. You need to specify the exact <strong>.shp extension</strong> to the read_file() method, like this:</p><pre># Shapefile is located in the data folder.<br>&quot;data/erosion_hotspots.shp&quot;</pre><h4>2. Do the same, and make sure your specify the output file type.</h4><p>I also forgot to specify the output file type and just passed in the folder where I wanted the GeoJSON to be saved. That didn’t work either. Make sure to include the <strong>.geojson</strong> extension in your filename!</p><pre># GeoJSON is also to be saved in the data folder.<br>&quot;data/erosion_hotspots.geojson&quot;</pre><h4>3. You have to include driver=&quot;GeoJSON&quot; when saving</h4><p>GeoPandas will default to writing another shapefile unless you tell it explicitly to write GeoJSON. Make sure to do this. (Scroll up to see the code).</p><h4>4. CRS (Coordinate Reference System)</h4><p>Make sure to check the CRS used by your shapefile, otherwise your data may not load up on your Leaflet.js map. Scroll up to see how I used <strong>.to_crs()</strong> method to fix this.</p><h4>5. Licencing and version control tip!</h4><p>If you’re working with datasets that have licencing or usage restrictions, make sure not to commit them to your Github! Especially if your repo public, these files will be visible to everyone.</p><p>Use a <strong>.gitignore file</strong> to keep them out of your commits. I forgot to do this and had to rewrite Git history to remove a sensitive file. Not fun 😅</p><p>This is one of the first real-world geospatial problems I tackled through code, and it felt great to figure it out. Using Python and GeoPandas made the process straightforward and reusable for my other datasets. If you’re also working on a Leaflet.js map, or just need to convert shapefiles into web-ready GeoJSON data format, I hope this guide helped!</p><p>Thanks for reading my <strong>first-ever Medium post</strong>! More to come as I document my progress in geospatial data, full-stack development, and beyond.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b20347c5ea92" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>