<?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 Nimendra Gunawardana on Medium]]></title>
        <description><![CDATA[Stories by Nimendra Gunawardana on Medium]]></description>
        <link>https://medium.com/@nimendra_ag?source=rss-5d040fef054a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*l9oC-9FI1Yh_muK-kuXUMA.png</url>
            <title>Stories by Nimendra Gunawardana on Medium</title>
            <link>https://medium.com/@nimendra_ag?source=rss-5d040fef054a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 20:55:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nimendra_ag/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[Point Clouds: Everything You Need to Know Before Getting Started]]></title>
            <link>https://medium.com/@nimendra_ag/point-clouds-everything-you-need-to-know-before-getting-started-49132c55ce25?source=rss-5d040fef054a------2</link>
            <guid isPermaLink="false">https://medium.com/p/49132c55ce25</guid>
            <category><![CDATA[3d-deep-learning]]></category>
            <category><![CDATA[physical-ai]]></category>
            <category><![CDATA[3d-vision]]></category>
            <category><![CDATA[point-cloud]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Nimendra Gunawardana]]></dc:creator>
            <pubDate>Tue, 20 Oct 2026 15:52:02 GMT</pubDate>
            <atom:updated>2026-10-21T04:38:58.092Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dhriBiBEyq_0CL2a" /><figcaption>Photo by <a href="https://unsplash.com/@leo_visions_?utm_source=medium&amp;utm_medium=referral">Leo_Visions</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As I started my research on 6DoF grasping of a robot arm, one term kept appearing in every paper I read: point clouds. I was curious, so I dug deeper. I quickly realised that point clouds were the very first thing I needed to understand. This article is a beginner’s guide to everything I learnt about point clouds. If you are interested in physical AI or 3D deep learning, point clouds are something you need to understand well.</p><p>A point cloud is a collection of 3D data points in space that map the external surface geometry, shape, and physical features of an object or environment. Let me make this clearer. When you consider 2D images, they consist of pixels. Each pixel has a value related to its colour. But the problem with 2D images is that they do not contain any <strong>depth </strong>information.</p><p>But why do we need depth at all? Suppose you are developing a vision model for a self-driving car, or training a model for a robot arm to perform 6DoF object grasping. Do you think processing only the colour of objects captured through a camera is enough? Not at all. Depth plays a vital role here. Without depth, your model has no idea where an object is located in 3D space. So the next question is: how do we encode depth information as input to the model? That is exactly where point clouds come in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NuFMag7O3zVGaQash69Ogg.png" /><figcaption>An RGB image and its point cloud from different angles.</figcaption></figure><p>The image above shows a real-world example from a robotics dataset. The top left is an RGB image of a cluttered scene, and the remaining views are its corresponding point cloud rendered from two different angles. Notice how the point cloud captures the scene&#39;s 3D structure, something a regular 2D image cannot provide. This example is taken from the GraspNet-1Billion dataset by Fang et al., which is widely used in robotic 6DoF grasp pose detection research.</p><p>As I discussed earlier, a point cloud maps the 3D world to a collection of points in Euclidean space, capturing the geometrical properties of the environment.</p><p>Let’s go into the technical details.</p><p>A point cloud is an unordered set of points in 3D space, where each point is described at minimum by its x, y, z coordinates. Point clouds are usually generated by LiDAR sensors or depth cameras (RGB-D cameras). However, we can also create a point cloud from scratch. The code snippet below generates a point cloud without any LiDAR or RGB-D camera.</p><p>Run the code below to generate a sphere-shaped point cloud.</p><pre>import numpy as np<br>import open3d as o3d<br>import matplotlib.pyplot as plt<br>import os<br> <br>rng = np.random.default_rng(seed=42)<br><br>N = 4069<br>theta = rng.uniform(0, np.pi, N)<br>phi   = rng.uniform(0, 2 * np.pi, N)<br><br>sphere_pts = np.column_stack([<br>    np.sin(theta) * np.cos(phi),<br>    np.sin(theta) * np.sin(phi),<br>    np.cos(theta),<br>])<br><br>pcd = o3d.geometry.PointCloud()<br>pcd.points = o3d.utility.Vector3dVector(sphere_pts)<br><br>z = sphere_pts[:, 2]<br>z_norm = (z - z.min()) / (z.max() - z.min())<br> <br>cmap = plt.get_cmap(&quot;plasma&quot;)<br>colours_gradient = cmap(z_norm)[:, :3]<br><br>sphere_gradient_pcd = o3d.geometry.PointCloud()<br>sphere_gradient_pcd.points = o3d.utility.Vector3dVector(sphere_pts)<br>sphere_gradient_pcd.colors = o3d.utility.Vector3dVector(colours_gradient)<br><br>os.makedirs(&quot;pcd_output&quot;, exist_ok=True) <br>o3d.io.write_point_cloud(&quot;pcd_output/sphere.ply&quot;, sphere_gradient_pcd)</pre><p>You can see the generated sphere-shaped point cloud in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*QemYErC4_-2BZ4KpkOexBQ.png" /><figcaption>A sphere-shaped point cloud.</figcaption></figure><p>Now, the next important topic is how we process point clouds.</p><p>Point clouds are not structured like images. They are unordered and irregular. Therefore, researchers have come up with processing techniques that are quite different from those used for 2D images.</p><p>Let’s look at some of the most commonly used point cloud processing techniques.</p><h4>Farthest Point Sampling (FPS)</h4><p>This is a sampling technique. But why do we need sampling at all? A raw point cloud from a LiDAR or depth camera can have <strong>100,000+ points</strong>. If you feed all of them into a neural network, it becomes computationally expensive. So we need to reduce the point cloud to a manageable size. Say, from 1024 down to 64 points. But which 64 points do you pick?</p><p>The naive approach is random sampling. You just pick random points. Simple, but it cannot guarantee that the selected points accurately represent the original point cloud. Large regions may be left out entirely. The solution is Farthest Point Sampling (Eldar et al.). In simple terms, FPS samples your point cloud while guaranteeing that the selected points are as spread out as possible across the shape. No large gaps. Every region is represented. FPS is widely used in 3D deep learning architectures such as PointNet++ (Qi et al.).</p><p>Now that we can sample our point cloud efficiently with FPS, the next question is: what do we do with those selected points? That is where kNN comes in.</p><h4>K-Nearest Neighbours (kNN)</h4><p>This is the same well-known machine learning algorithm, applied to point clouds. In 2D images, finding the neighbours of a particular pixel (x, y) is straightforward — they are always at (x±1, y±1), hardcoded by the grid, and convolution can be applied directly.</p><p>In a point cloud, there is no grid. Point 42 and point 43 might be on opposite sides of the object. To apply any local operation such as convolution, you first have to find who the neighbours are. That is where kNN comes in.</p><p>So what exactly does kNN do? kNN takes each of the, say, 64 FPS-selected centroids and asks: “Who are the 16 closest points to me in the original 1024-point cloud?” Those 16 neighbours form a local patch, which is the 3D equivalent of a convolution window in a 2D CNN. The network then learns features from that patch.</p><h4>Surface Normal Estimation</h4><p>A point cloud gives you isolated dots in space. There are no triangles, no mesh, no explicit surface. So how do you figure out which way the surface is facing at each point?</p><p>A surface normal at a point is a unit vector that points perpendicular to the surface at that location. This is useful for determining which way is “outward” from an object, and whether a surface is flat, curved, or an edge. The algorithm behind surface normal estimation is mathematically rich. It involves covariance matrices and eigenvalue decomposition. I will not go into the mathematics here, but if you are interested, you can read more in this <a href="https://www.mdpi.com/2673-8244/6/3/63"><em>article</em></a>.</p><h4>Voxel Downsampling</h4><p>This is also a sampling technique. Imagine overlaying a 3D grid of cubes across the entire point cloud space. Each little cube is called a voxel (short for volumetric pixel). All points that fall inside the same voxel are replaced by their centroid, which is the mean of their coordinates.</p><p>Consider a voxel size of 1 unit, and five points P1 to P5:</p><pre>P1 = (0.1, 0.2, 0.3)<br>P2 = (0.8, 0.6, 0.7)   &lt;- same voxel as P1 (all coords in [0,1))<br>P3 = (0.5, 0.9, 0.4)   &lt;- same voxel as P1<br>P4 = (1.2, 0.3, 0.5)   &lt;- different voxel (x is in [1,2))<br>P5 = (1.7, 0.8, 0.2)   &lt;- different voxel (x is in [1,2))</pre><p>One important thing to note is that the output points from voxel downsampling are computed averages. They may not correspond to any point that actually existed in the original cloud.</p><h4>Denoising Point Clouds</h4><p>Real sensors add noise and occasionally produce wildly incorrect points, commonly referred to as outliers. This noise can be removed using statistical outlier removal techniques, which work as follows:</p><ol><li>For each point, compute the mean distance to its <em>nb_neighbors </em>nearest neighbours.</li><li>Compute the global mean (μ) and standard deviation (σ) of those distances.</li><li>Remove any point whose mean-neighbour-distance &gt; μ + std_ratio × σ.<br>Point-wise Segmentation.</li></ol><h4>Point-wise Segmentation</h4><p>In image segmentation, every <strong>pixel </strong>gets a class label. In point cloud segmentation, every <strong>point </strong>gets a class label.</p><pre>Example:<br>Point at (0.30, -0.10, 0.81) -&gt; label=3 (ball)<br>Point at (-0.20, 0.10, 0.83) -&gt; label=2 (mug)<br>Point at (0.00, 0.00, 0.75) -&gt; label=1 (table)</pre><h4>Random Sample Consensus (RANSAC) Plane Fitting</h4><p>Suppose you have a point cloud of a room and you want to automatically find the floor without anyone telling you where it is. The floor is a plane, so the question becomes: find the plane that best fits the data.</p><p>RANSAC works by randomly sampling a tiny set of points, fitting a model to them, then counting how many of the remaining points agree with that model. This is repeated many times, and the plane with the most agreement wins. I will not go into the full algorithm here, but if you are interested, this <a href="https://www.youtube.com/watch?v=MJJNIvvAQzc"><em>video</em></a><em> </em>explains it clearly.</p><h4>Point clustering</h4><p>You can cluster the points of a point cloud using algorithms such as DBSCAN or HDBSCAN. These algorithms group spatially close points together, effectively separating distinct objects in the scene while also helping to remove noise.</p><p>I also found this interesting <a href="https://www.youtube.com/watch?v=kqq2qekP_rQ"><em>video</em></a><em> </em>on a process called <em>Scan-to-BIM.</em> It involves using LiDAR technology to capture precise 3D point cloud data of a physical structure, then converting this data into a <em>Building Information Model (BIM),</em> which is a comprehensive digital representation, aiding in design, construction, and maintenance processes.</p><p><em>Conclusion</em></p><p><em>Point clouds are the foundation of modern 3D perception. From self-driving cars to robotic grasping, they give machines the ability to understand the physical world in three dimensions.</em></p><p><em>In this article, we covered the core concepts: what a point cloud is, why depth matters, how they are captured, and the key processing techniques that are used in 3D deep learning pipelines. These are not isolated ideas. FPS selects the right points, kNN finds their neighbours, and together they form the backbone of architectures like PointNet++ and models like POINT-SAM.</em></p><p>I hope this article covers basic yet important concepts you need to get started with point clouds. Thank you for reading, and feel free to leave your comments or share any ideas about point clouds in the section below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49132c55ce25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Challenges and Learnings in Density-Based Clustering for Business Data]]></title>
            <link>https://medium.com/@nimendra_ag/challenges-and-learnings-in-density-based-clustering-for-business-data-c2016de13cf2?source=rss-5d040fef054a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2016de13cf2</guid>
            <dc:creator><![CDATA[Nimendra Gunawardana]]></dc:creator>
            <pubDate>Sun, 31 May 2026 19:41:11 GMT</pubDate>
            <atom:updated>2026-05-31T20:12:38.121Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xwT5ZhQfIppa63B9" /><figcaption>Photo by <a href="https://unsplash.com/@hjkp?utm_source=medium&amp;utm_medium=referral">henry perks</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, I want to share my hands-on experiences with <strong>HDBSCAN</strong>, a clustering algorithm that’s great for finding patterns in complex, real-world data. I’ll talk about how it compares to DBSCAN, where it works well, and some challenges I faced while using it.</p><p>In data science, clustering refers to the process of grouping objects (or data) into distinct clusters such that the objects within each cluster share similar characteristics. The specific characteristics considered depend on the business requirements and the type of data being analyzed.</p><p>There are a lot of clustering methods available. Among them, <a href="https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html"><em>K-Means</em></a><em> </em>clustering is one of the most fundamental algorithms, which is quite easy to understand and implement. With the ease of K-Means clustering, however, come certain limitations. Even though predefining the number of clusters is a drawback, methods like <a href="https://scikit-learn.org/stable/auto_examples/cluster/plot_kmeans_silhouette_analysis.html#sphx-glr-auto-examples-cluster-plot-kmeans-silhouette-analysis-py"><em>silhouette analysis</em></a> can help determine an appropriate value for K. However, one of the main limitations of K-Means, which is inherent to the algorithm, is its sensitivity to outliers, which are common in noisy, real-world business data.</p><p>That’s when the DBSCAN (Density-based Spatial Clustering of Applications with Noise) comes into play. As its name indicates, this algorithm is capable of handling noisy data. The clustering algorithm in DBSCAN mainly depends on its two parameters, <em>min_sample </em>and <em>eps</em>. The parameter <em>min_samples </em>indicates the number of data points in a neighborhood for a point to be considered as a core point. The parameter eps is the maximum distance between two datapoints to be defined as one in the neighbourhood of the other datapoint. This is how the algorithm works. First starts with a random point. Draw a circle with a radius of <em>eps </em>and the center as the data point. Count the number of datapoints located in that circle. If the number of datapoints (including itself) is equal to or greater than <em>min_samples, </em>then that datapoint is considered a core point. What if the number of data points in that circle is less than <em>min_count</em>?</p><p>To be more specific, there are 3 types of points that the clustering algorithm identifies.</p><blockquote>Core points — A data point is a core point if at least <em>min_samples </em>points are located within the distance <em>eps </em>of it.</blockquote><blockquote>Border points — A data point is a border point if it is reachable from a core point (distance to nearest core point is less than or equal to <em>eps</em>) but not a core point itself.</blockquote><blockquote>Noise points — Neither core point nor border point.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*q_rYNsIz6YujjG-cL81Lyw.png" /></figure><p>Looking at the image above, if <em>eps </em>is set to a certain value, and <em>min_samples </em>is 5, then the point <strong>X</strong> will be considered a <strong>core point</strong>.</p><p>This is how DBSCAN identifies noise. You can adjust the values of the above parameters to redefine which points are considered noise, core, and border points within the dataset. With these adjustments, DBSCAN clusters data points into different groups in a way that is robust to noise. It can effectively handle noisy data and outliers.</p><p>So far, everything sounds perfect. But the real challenges arise when working with real-world business data.</p><p>The problem with the DBSCAN is that it has a <strong>static definition</strong> for the <strong><em>density region</em></strong>. But what is this density region? The definition you provide to the density region is the most important factor that controls the output of the algorithm. The spatial clustering is all about distinguishing the regions with high density from the sparse regions. Therefore, when working with data with high variety and a big diversity in real-world scenarios, we need a more dynamic definition for the <strong>density region</strong>. This is where the HDBSCAN algorithm becomes important. HDBSCAN can dynamically adjust to the different densities and forms of clusters in the data, producing more reliable and adaptable clustering results.</p><blockquote>A good real-world example of this can be seen in customer location clustering for retail store placement. In urban areas, customers are located very close to each other, forming dense clusters, while in rural areas, customers are more spread out, creating sparser clusters. If DBSCAN is used, a single fixed value for parameters such as <em>eps</em> and <em>min_samples</em> must be chosen. A small <em>eps </em>value might correctly identify the dense urban clusters but fail to capture the rural ones, while a larger value could merge nearby urban clusters into one big cluster. This happens because DBSCAN assumes all clusters have similar density. However, <strong>HDBSCAN </strong>can automatically adapt to both dense and sparse regions, correctly identifying clusters in both city and rural areas. This makes it much more effective for handling complex, real-world data distributions.</blockquote><p>Let’s see how HDBSCAN works.</p><p>HDBSCAN can be considered an extension of DBSCAN. The high-level idea is that HDBSCAN builds a <strong>hierarchy of density-based clusters</strong> and then extracts the most <strong>stable</strong> clusters from that hierarchy, so it can find clusters of different densities and sizes while removing noise. But under the hood, it consists of a lot of mathematics, which I’m expecting to discuss in a separate article.</p><p>Let’s see the important parameters in the HDBSCAN algorithm.</p><blockquote>min_cluster_size — The minimum number of datapoints required to form a cluster. Increasing this can cause a decrease in the number of output clusters.</blockquote><blockquote>min_samples <strong>— </strong>For every point, the algorithm computes a <strong>core distance</strong>, which is the distance from that point to its <em>k-th </em>nearest neighbour (<em>k is the value assigned to this parameter</em>).</blockquote><blockquote>cluster_selection_epsilon — This is a distance. Clusters below this value will be merged.</blockquote><blockquote>metric — The metric used to calculate the distance between datapoints. This is crucial when working with different types of data. The default value is ‘<strong><em>euclidean’. </em></strong>But the value should be adjusted accordingly when you are working with different types of data. As an example, if you are working with geospatial data such as latitude and longitude values, you should change it to ‘<strong><em>haversine</em></strong>’.</blockquote><blockquote>store_centers — This parameter does not directly affect the clustering process, but when the center point of a cluster is defined, which can be very important in some business applications, this parameter becomes important. And this is something that you can not find in DBSCAN.</blockquote><p>Other than the above parameters, some other parameters in HDBSCAN become important in some scenarios. You can find them in this <a href="https://scikit-learn.org/stable/modules/generated/sklearn.cluster.HDBSCAN.html"><em>documentation</em></a>.</p><p>One drawback I noticed with HDBSCAN is that it lacks an explicit parameter to control the maximum distance between two points within a cluster. DBSCAN also doesn’t offer such a parameter. Using the same dataset with both algorithms, HDBSCAN often produces a larger number of clusters because it detects clusters at multiple density levels. However, this can sometimes produce clusters that are not meaningful for a particular business use case. I faced this issue in practice. The behaviour depends on your application and data, so it would be useful if HDBSCAN offered a parameter to limit the maximum intra-cluster distance. However, I should mention that this case was very rarely seen in the output, and the HDBSCAN gave me better results when compared to DBSCAN.</p><p>This is my experience of using DBSCAN and HDBSCAN with real-world business data. While DBSCAN is simple and effective for datasets with relatively uniform densities, it struggles when clusters vary significantly in density, requiring careful tuning of the <em>eps </em>and <em>min_samples </em>parameters. This also highlights the importance of understanding the dataset and the business requirements and choosing the algorithm that best fits the requirements. I would like to mention that this article is based purely on my practical experience, and the results may vary depending on different business requirements.</p><p>I would love to hear your thoughts and ideas, especially regarding the scenarios I struggled with — feel free to comment below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2016de13cf2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploratory Data Analysis and Basic Data Structures in R]]></title>
            <link>https://medium.com/@nimendra_ag/exploratory-data-analysis-and-basic-data-structures-in-r-bc791a5fa858?source=rss-5d040fef054a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc791a5fa858</guid>
            <category><![CDATA[statistical-analysis]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[r-language]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Nimendra Gunawardana]]></dc:creator>
            <pubDate>Thu, 13 Mar 2025 06:35:34 GMT</pubDate>
            <atom:updated>2025-03-13T06:35:34.377Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uTz9t8ydGyjrjF5d" /><figcaption>Photo by <a href="https://unsplash.com/@matthiasoberholzer?utm_source=medium&amp;utm_medium=referral">Matthias Oberholzer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Exploratory Data Analysis</h3><p>Exploratory Data Analysis (EDA) is an essential process in data science that involves identifying insights or patterns in data. This process is crucial as it allows the researcher to understand how the data elements are distributed and how they interact with each other. By thoroughly analysing these insights and patterns, the researcher can draw more accurate and reliable conclusions and make informed decisions.</p><p>In this article, as well as in the next couple of articles, I will be discussing the significance of EDA within the data science workflow.</p><p>First, let’s explore the history of EDA.</p><p><a href="https://en.wikipedia.org/wiki/John_Tukey"><em>John W. Tukey</em></a>, an American mathematician and statistician, first came up with the concept of exploratory data analysis in his book published in 1977, also titled<em> Exploratory Data Analysis</em>. Tukey emphasized the importance of visually exploring data before feeding statistical models. His approach was to analyze data visually rather than solely relying on traditional statistical methods. And it was not a miracle as by the 1970s, sufficient computational power had become available, making the visual display of data practical. Therefore, the researchers started using graphical methods such as histograms, box plots, and scatter plots to understand data distributions, spot anomalies, and perform many other statistical analyses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*1b08BAlYVzokYJSJUnm7Lw.jpeg" /><figcaption>John W. Tukey — An American statistician and mathematician</figcaption></figure><h3>Elements of Structured Data</h3><p>Today, with the advancement of digital technology, data originates from various resources, including sensors, images, videos, audios, and events. While this original raw data is often unstructured, it can be represented using structured formats for analysis. Images are grids of numbers, videos are sequences of those grids, and texts are a sequence of characters that can be converted into a meaningful numerical representation. Similarly, audio signals are sequences of amplitude values over time. In many cases, to apply statistical concepts behind EDA, this unstructured data needs to be turned into structured data.</p><p>This process of structuring data needs a clear understanding of data type taxonomy. Having a concrete idea of the taxonomy of data types is important in many cases. Especially when working with data analysis and machine learning. In EDA, the data type is also used to identify the suitable visual display method and statistical model. Most importantly, when working with data analysis software such as Python and R, using the correct data type causes an increase in the performance of these software programs.</p><p>These are the commonly used data types in the R language.</p><ol><li><strong>Continuous </strong>— Data that can take any value. Examples are <em>Height</em>, <em>Weight</em>, <em>Temperature, etc</em>.</li><li><strong>Discrete </strong>data consists of distinct countable values that can not form a continuous range. Sometimes, categorical data also belong to this data type. Possible examples are <em>shoe sizes</em>, <em>number of students in a classroom</em>, t<em>ype of vegetables</em> (categorical)<em>, etc</em>.</li><li><strong>Categorical </strong>— Refers to data that represents categories or labels, rather than numerical values. Examples are <em>Gender, Marital Status, Genre of a song, etc</em>.</li><li><strong>Ordinal </strong>— Categorical data that has an explicit order. An example is the <em>Safety Level (Very High, High, Moderate, Low, Very Low).</em></li><li><strong>Non-ordinal/ nominal</strong> — Categorical data that has no order. Examples are <em>Gender, School, etc</em>.</li><li><strong>Binary </strong>— Categorical data that has only two possible values. Examples are <em>Presence/ Absence, Pass/ Fail, etc</em>.</li></ol><p>After talking about the fundamental data types–continuous, discrete, and categorical—and their importance in EDA and how they impact data analysis, let’s examine how R, one of the most popular programming languages for data analysis and statistics, handles and represents these data types.</p><h3>Atomic Data Types in R</h3><p>Represents the simplest form of data that can not be further broken into smaller components. Combining these atomic data types allows the formation of more complex data types.</p><h4>Logical</h4><p>The boolean data type has two possible values: <em>TRUE </em>and <em>FALSE</em>. It is essential for dealing with logical conditions and Boolean operations. The code below provides a basic example of how the Logical data type is used.</p><pre># Boolean values in R are case-sensitive: TRUE and FALSE.<br>is_ready &lt;- TRUE<br>has_errors &lt;- FALSE<br><br>cat(is_ready, &quot;\n&quot;)<br>cat(has_errors, &quot;\n&quot;)<br><br># Example of using the boolean variables in a conditional statement.<br>if (is_ready &amp;&amp; !has_errors) {<br>  cat(&quot;The process can proceed.\n&quot;)<br>} else {<br>  cat(&quot;The process cannot proceed.\n&quot;)<br>}</pre><h4>Numeric</h4><p>This is the default data type for numerical values in the R language. This data type is used to store numerical values with decimal points. The following BMI calculating example shows how to use the Numeric data type.</p><pre>weight_kg &lt;- 70.6  <br>height_m &lt;- 1.75<br><br># Calculate BMI<br>bmi &lt;- weight_kg / (height_m^2)<br><br># Print the result<br>cat(&quot;Your BMI is:&quot;, bmi)</pre><h4>Integers</h4><p>The Integer data type is used to store whole numbers. When assigning integer values to variables, use the suffix ‘L’. This suffix explicitly specifies that a particular number should be stored as an integer instead of the Numeric (default) type.</p><h4><strong>Complex</strong></h4><p>The Complex data type in R represents the numbers with real and imaginary parts, enabling complex number operations. The following example shows you a basic arithmetic operation performed using complex numbers.</p><pre># Assig complex number to variables<br>z1 &lt;- 3 + 2i  # Creates a complex number 3 + 2i<br>z2 &lt;- complex(real = 1, imaginary = -4) # Creates 1 - 4i<br><br># Basic arithmetic operations using complex numbers <br>z3 &lt;- z1 + z2<br>z4 &lt;- z1 * z2<br>print(z3) # Output: 4 - 2i<br>print(z4) # Output: 11 - 10i<br><br># Extract the real and complex parts in a complex number<br>real_part &lt;- Re(z3)<br>imag_part &lt;- Im(z4)<br><br>print(real_part) # Output: 4<br>print(imag_part) # Output: -10</pre><h4>Character</h4><p>This data type in R is used to represent textual data, dealing with any sequence of characters such as words and sentences.</p><pre># Basic Character Assignment<br>name &lt;- &quot;Nimendra Gunawardana&quot; # Single or double quotes work<br>city &lt;- &#39;Colombo&#39; <br><br>print(name)<br>print(city)<br><br># Concatenating Strings<br>greeting &lt;- paste(&quot;Hello,&quot;, name, &quot;from&quot;, city, &quot;!&quot;)<br>print(greeting)<br><br># Extracting Substrings<br>text&lt;- &quot;This is a demo sentence.&quot;<br>substring &lt;- substr(text, 6, 9) # Extracts &quot;is a&quot;<br>print(substring)<br><br># Converting to Uppercase/Lowercase<br>text &lt;- &quot;This is a Demo Text&quot;  # a mixed case text<br>uppercase &lt;- toupper(text)<br>lowercase &lt;- tolower(text)<br>print(uppercase)<br>print(lowercase)</pre><p>These are the most fundamental data types in the R programming language, which you can use to form other complex data types. Let’s dive into R’s other data types.</p><h3>Vectors</h3><p>In R, Vectors represent collections of data elements of the same data type. This allows for efficient storage and manipulation. You can use the <em>c() </em>function to create a Vector type variable and separate the items using a commas.</p><pre># Integer Vector<br>integer_vector &lt;- c(10L, 20L, 30L, 40L, 50L) # The L suffix is important!<br>print(integer_vector)<br>print(typeof(integer_vector)) # Output: &quot;integer&quot;<br><br># Numeric (Double) Vector<br>numeric_vector &lt;- c(1.5, 7.7, 9.3, 22.4, 25.5)<br>print(numeric_vector)<br>print(typeof(numeric_vector)) # Output: &quot;double&quot;<br><br># Character Vector<br>character_vector &lt;- c(&quot;cricket&quot;, &quot;football&quot;, &quot;chess&quot;, &quot;basketball&quot;)<br>print(character_vector)<br>print(typeof(character_vector)) # Output: &quot;character&quot;</pre><p>Lists are a special type of vector. A list can consist of data of different categories. Use the list() function, and items are separated by commas.</p><pre># A simple list with various data types<br>my_list &lt;- list(1, TRUE, &quot;hello&quot;, 3.14)<br>print(my_list)<br><br># A list with named elements<br>person_info &lt;- list(age = 23, is_student = TRUE, name = &quot;Nimendra&quot;, Height= 1.76)<br>print(person_info)</pre><h3>Matrices and Arrays</h3><p>A matrix is a two-dimensional data structure that organizes data of the same type. The R language provides the <em>matrix()</em> function to create a matrix.</p><pre># Creating a Basic Matrix<br>matrix1 &lt;- matrix(1:9, nrow = 3, ncol = 3)<br>print(matrix1)<br><br># Creating a Matrix with Specified Data<br>data &lt;- c(1, 2, 3, 4, 5, 6)<br>matrix2 &lt;- matrix(data, nrow = 2, ncol = 3, byrow = TRUE) #byrow fills by row instead of column<br>print(matrix2)<br><br># Creating a Character Matrix<br>matrix3 &lt;- matrix(c(&quot;cricket&quot;, &quot;football&quot;, &quot;chess&quot;, &quot;basketball&quot;), nrow = 2, ncol = 2)<br>print(matrix3)<br><br># Accessing Matrix Elements<br>print(matrix1[2, 3]) # element in the 2nd row, 3rd column<br>print(matrix2[1, ]) # the first row<br>print(matrix3[, 2]) # the second column<br><br># Example 5: Matrix Arithmetic<br>matrix4 &lt;- matrix(1:4, nrow = 2, ncol = 2)<br>matrix5 &lt;- matrix(5:8, nrow = 2, ncol = 2)<br>matrix_sum &lt;- matrix4 + matrix5<br>matrix_product &lt;- matrix4 %*% matrix5 # Matrix multiplication<br>print(matrix_sum)<br>print(matrix_product)</pre><p>An Array is a multi-dimensional extension of a Matrix. It can have more than two dimensions.</p><pre># Creating a 3-Dimensional Array<br>array1 &lt;- array(1:24, dim = c(4, 3, 2)) # 4 rows, 3 columns, 2 layers<br>print(array1)<br><br># Creating a 2-Dimensional Array (Equivalent to a Matrix)<br>array2 &lt;- array(1:9, dim = c(3, 3))<br>print(array2)<br><br># Accessing Array Elements<br>print(array1[2, 3, 1]) # Accessing element at 2nd row, 3rd column, 1st layer<br>print(array1[, 2, ]) # Accessing 2nd column across all rows and layers</pre><h3>Data Frames</h3><p>A Data Frame in R is a two-dimensional table-like data structure that can hold data with different types. (Columns in dataframe can be in different types such as Integers, Numeric, and Character, etc).</p><pre># Creating a Basic Data Frame<br>name &lt;- c(&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;, &quot;David&quot;)<br>age &lt;- c(25, 30, 28, 35)<br>city &lt;- c(&quot;New York&quot;, &quot;London&quot;, &quot;Paris&quot;, &quot;Tokyo&quot;)<br>is_student &lt;- c(TRUE, FALSE, FALSE, TRUE)<br><br>df &lt;- data.frame(name, age, city, is_student)<br>print(df)<br><br># Accessing Data Frame Columns<br>print(df$name)<br>print(df$age)<br>print(df[, &quot;city&quot;]) # Accessing by column name<br>print(df[, 3]) # Accessing by column index<br><br># Accessing Data Frame Rows<br>print(df[1, ]) # Accessing the first row<br>print(df[df$age &gt; 30, ]) # Accessing rows based on a condition</pre><h3>Factors</h3><p>In the R language, factors are used to store categorical data. Use the <em>factor()</em> function and use a vector as the argument.</p><pre># Example: Creating a Factor with Automatic Level Ordering<br><br>sports &lt;- c(&quot;rugby&quot;, &quot;basketball&quot;, &quot;cricket&quot;, &quot;rugby&quot;, &quot;hockey&quot;, &quot;basketball&quot;)<br>sport_factor &lt;- factor(sports)<br><br>print(sport_factor)<br>print(levels(sport_factor))</pre><p><em>output:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*qsU0JRLckNkhaBb-4NONpw.png" /></figure><p>In the example, you can see the levels or the order has been printed automatically. The order is in the alphabetical order of the words.</p><p>Or you can set the order manually as below.</p><pre># Creating a Factor with Manual Level Ordering<br><br>sports &lt;- c(&quot;rugby&quot;, &quot;basketball&quot;, &quot;cricket&quot;, &quot;rugby&quot;, &quot;hockey&quot;, &quot;basketball&quot;)<br><br># Specify the desired order of levels<br>sport_factor &lt;- factor(sports, levels = c(&quot;cricket&quot;, &quot;hockey&quot;, &quot;basketball&quot;, &quot;rugby&quot;))<br><br>print(sport_factor)<br>print(levels(sport_factor))</pre><p><em>output:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*xRNasBN1gFUHs_NOEGUfUQ.png" /></figure><p>Now that we have explored different data types and structures in R, let’s move on to rectangular data, one of the most commonly used formats in data analysis.</p><h3>Rectangular Data</h3><p>The rectangular data structure is used as a general form of data in data analysis. The name <em>Rectangular Data </em>comes with its tabular format. It is a two-dimensional matrix that consists of rows and columns, where each row represents a single instance of data, and each column represents a single feature. Data doesn’t always originally come in this way; unstructured data needs to be processed and prepared as rectangular data.</p><pre># Install and load necessary packages<br>install.packages(&quot;titanic&quot;)  # Install Titanic dataset package if not installed<br>install.packages(&quot;knitr&quot;)    # Install knitr package if not installed<br><br>library(titanic)<br>library(knitr)<br><br># Load Titanic dataset<br>df &lt;- titanic::titanic_train  <br><br># Display the first 10 rows in a nicely formatted table<br>print(kable(head(df, 10)))</pre><p><em>output:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2d-nUybqMNwCowu9gZjLVg.png" /></figure><p>Refer to <a href="https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/data.frame">r dataframe documentation</a> for more information.</p><p>This article covered the fundamentals of Exploratory Data Analysis (EDA) and basic data types in R, from atomic types to data frames. Understanding these elements is important for effective data manipulation and analysis in R, laying a strong foundation for further data science work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc791a5fa858" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>