Skip to content
Back to exploration
Mathematical modeling / English

Rapid R: K-Means Clustering in 3 Minutes! | R Programming Quick Reference

Data Within Reach · YouTube · 2:17

Open original
READ & KEEP

The explanation, unpacked.

Reviewed learning material · Video analysis · English
Read the full overview

This introductory tutorial demonstrates how to perform and visualize K-means clustering in R using the built-in iris dataset. The speaker defines K-means as an algorithm for partitioning data into distinct, non-overlapping groups. The process involves loading the data, subsetting it to the first four columns, setting a random seed for reproducibility, and applying the kmeans function to create three clusters. The resulting object, which contains cluster assignments and center coordinates, is then printed to the console. Finally, the tutorial shows how to visualize these clusters using a scatter plot, coloring the data points by their cluster assignment and adding large points to represent the calculated cluster centers. This video segment demonstrates how to perform k-means clustering on the iris dataset using R. It shows the R code required to execute the clustering algorithm and visualize the results using a scatter plot, where data points are colored by cluster and cluster centers are marked with distinct symbols.

Use the learning inspector for key ideas and moments, or open the reading tabs for the complete notes.

Chapters

0:00Introduction to K-means Clustering0:36Preparing the Iris Dataset in R0:56Executing the K-means Algorithm1:30Visualizing Clusters with a Scatter Plot2:00Introduction and Call to Action2:05R Code for K-Means Clustering and Visualization2:10Outro

Learning script

Generated from the video's visuals and explanation; not verbatim speech.

The video begins with an introduction to the topic of unsupervised learning, specifically focusing on K-means clustering.

K-means is defined as a popular algorithm used to partition data into distinct, non-overlapping groups, which can help uncover hidden patterns or rethink existing categories.

The practical demonstration starts in the RStudio environment by loading the built-in iris dataset using the command data(iris).

A new variable, iris_data, is created to hold only the first four columns of the dataset, simplifying the data for the clustering exercise.

The random number generator seed is set with set.seed(54321) to ensure reproducibility, followed by executing the kmeans function to partition the data into three clusters.

The speaker explains that the resulting kmeans object contains valuable information, including a cluster assignment for each data point and the coordinate location of each cluster's center.

The output object is printed to the console to inspect the cluster means and the clustering vector.

To visualize the results, a scatter plot is generated using Sepal.Length and Sepal.Width, with data points colored according to their assigned cluster.

Finally, the calculated cluster centers are added to the plot as large, distinct points, providing a clear visual representation of the partitioned groups.

The speaker concludes the tutorial, encouraging viewers to like, share, and subscribe, and to leave comments with suggestions for future topics.

The screen displays R code demonstrating how to use the `kmeans` function to cluster the `iris_data` into 3 centers. The results are stored in `kmeans_iris_result`. The code then uses the `plot` function to create a scatter plot of `Sepal.Length` versus `Sepal.Width`, coloring the points based on their assigned cluster (`kmeans_iris_result$cluster`). Finally, the `points` function is used to add the cluster centers to the plot, represented as large diamond shapes.

The video ends with a logo animation for 'DATA within REACH'.

Knowledge cards

01

Definition of K-means Clustering

K-means is a popular clustering algorithm used to partition data into distinct, non-overlapping groups. It helps uncover hidden patterns or rethink categories.

02

Running K-means in R

The kmeans function in R performs clustering. It requires a dataset and the number of centers (clusters) as arguments. Setting a random seed beforehand ensures reproducible results.

kmeans(data,centers=k)kmeans(data, centers = k)
03

K-means Output Object Structure

The object returned by the kmeans function contains essential data, specifically a cluster assignment for each data point and the coordinate location of the center of each cluster.

04

Visualizing Clusters with a Scatter Plot

Clusters can be visualized using a scatter plot of at least two variables. Data points are colored according to their cluster assignment, and the cluster centers are plotted as large points to highlight their locations.

05

K-Means Clustering in R

Use the `kmeans()` function to perform clustering. Specify the dataset and the number of centers (clusters).

kmeans(data,centers)kmeans(data, centers)
06

Visualizing Clusters in R

Use `plot()` to create a scatter plot of your features, setting the `col` argument to the cluster assignments from your `kmeans` result. Use `points()` to overlay the cluster centers.

plot(x,y,col=clusters)points(centers,col=1:k,pch=23,cex=3)plot(x, y, col=clusters) points(centers, col=1:k, pch=23, cex=3)

Detailed learning notes

Explore conditions, steps and evidence. Supplementary explanations are labeled separately from content shown in the video.

Symbols · 18

iris

Clear evidence
Shown in the video
Evidence
  1. Audio
    Observation

    The speaker says to use the iris dataset and mentions the data command with iris.

  2. Formula
    Observation

    data(iris)

Symbol

iris

Meaning

Built-in R dataset used for the clustering example.

Domain

R dataset

iris_data

Clear evidence
Shown in the video
Evidence
  1. Audio
    Observation

    The speaker says to create a variable containing only the first four columns of the data.

  2. Formula
    Observation

    iris_data <- iris[,1:4]

Symbol

iris_data

Meaning

Subset of the iris dataset containing the first four columns.

Domain

R data frame

set.seed(54321)

Clear evidence
Shown in the video
Evidence
  1. Formula
    Observation

    set.seed(54321)

Uncertainties
  1. The speaker does not explicitly explain the purpose of set.seed in the audio.

Symbol

set.seed(54321)

Meaning

R function call that sets the random number generator seed before running kmeans.

Domain

R function call

kmeans_iris_result

Clear evidence
Shown in the video
Evidence
  1. Audio
    Observation

    The speaker says the kmeans function returns an object which includes lots of useful data.

  2. Formula
    Observation

    kmeans_iris_result <- kmeans(iris_data, centers = 3)

Symbol

kmeans_iris_result

Meaning

Object returned by the kmeans function containing cluster assignments and center coordinates.

Domain

R object

centers = 3

Clear evidence
Shown in the video
Evidence
  1. Audio
    Observation

    The speaker says to partition the data into three clusters.

  2. Formula
    Observation

    centers = 3

Symbol

centers = 3

Meaning

Argument specifying the number of clusters to form.

Domain

Integer parameter

Cluster assignment

Clear evidence
Shown in the video
Evidence
  1. Audio
    Observation

    The speaker says for each data point it includes a cluster assignment.

  2. Formula
    Observation

    Clustering vector:

Symbol

Cluster assignment

Meaning

The group label assigned to each data point by the kmeans algorithm.

Domain

Integer vector

Cluster center

Clear evidence
Shown in the video
Evidence
  1. Audio
    Observation

    The speaker says it also includes the coordinate location of the center of the cluster.

  2. Formula
    Observation

    Cluster means:

Symbol

Cluster center

Meaning

The coordinate location representing the mean of the points in a cluster.

Domain

Numeric vector

Sepal.Length

Clear evidence
Shown in the video
Evidence
  1. Formula
    Observation

    plot(iris_data[c("Sepal.Length", "Sepal.Width")], ...)

Symbol

Sepal.Length

Meaning

Variable plotted on the x-axis of the scatter plot.

Domain

Numeric variable

Sepal.Width

Clear evidence
Shown in the video
Evidence
  1. Formula
    Observation

    plot(iris_data[c("Sepal.Length", "Sepal.Width")], ...)

Symbol

Sepal.Width

Meaning

Variable plotted on the y-axis of the scatter plot.

Domain

Numeric variable

col

Clear evidence
Shown in the video
Evidence
  1. Audio
    Observation

    The speaker says the different colors represent the different clusters.

  2. Formula
    Observation

    col=kmeans_iris_result$cluster

Symbol

col

Meaning

Plot argument mapping cluster assignments to colors.

Domain

Plot parameter

pch=23

Clear evidence
Shown in the video
Evidence
  1. Formula
    Observation

    pch=23

Uncertainties
  1. The speaker does not explicitly explain what pch=23 means in the audio.

Symbol

pch=23

Meaning

Plot character argument specifying the shape of the points.

Domain

Plot parameter

cex=3

Clear evidence
Shown in the video
Evidence
  1. Audio
    Observation

    The speaker says the large point in the center represents the center of the cluster.

  2. Formula
    Observation

    cex=3

Symbol

cex=3

Meaning

Plot argument scaling the size of the center points to make them large.

Domain

Plot parameter

Knowledge points · 7

Definition of K-means clustering

Clear evidence
Shown in the video
Evidence
  1. Audio
    Observation

    K-means is a popular clustering algorithm used to partition data into distinct non-overlapping groups.

Definition
Explanation

K-means is defined as a clustering algorithm used to partition data into distinct, non-overlapping groups. It helps uncover hidden patterns or rethink categories.

Conditions
  1. Data must be partitionable into distinct groups.

  2. Groups are non-overlapping.

Using the kmeans function in R

Clear evidence
Shown in the video
Evidence
  1. Audio
    Observation

    Running k-means clustering is pretty straightforward. We're going to partition the data into three clusters... The kmeans function returns an object which includes lots of useful data.

  2. Formula
    Observation

    kmeans_iris_result <- kmeans(iris_data, centers = 3)

Method
Explanation

The kmeans function in R is used to perform clustering. It takes a dataset and a specified number of centers (clusters) as arguments, returning an object with cluster assignments and center coordinates.

Formula
kmeans(data,centers=k)kmeans(data, centers = k)
Conditions
  1. Requires a numeric dataset.

  2. Requires specifying the number of clusters (centers).

Prerequisites
  1. Definition of K-means clustering

Structure of kmeans output object

Clear evidence
Shown in the video
Evidence
  1. Audio
    Observation

    For each data point, it includes a cluster assignment, and it also includes the coordinate location of the center of the cluster.

  2. Formula
    Observation

    Cluster means: Clustering vector:

Definition
Explanation

The object returned by the kmeans function contains useful data, specifically a cluster assignment for each data point and the coordinate location of the center of each cluster.

Prerequisites
  1. Using the kmeans function in R

Visualizing clusters with a scatter plot

Clear evidence
Shown in the video
Evidence
  1. Audio
    Observation

    We'll use a scatter plot to display the clusters for at least two variables. The different colors represent the different clusters, and the large point in the center represents the center of the cluster.

  2. Formula
    Observation

    plot(iris_data[c("Sepal.Length", "Sepal.Width")], col=kmeans_iris_result$cluster) points(kmeans_iris_result$centers[,c("Sepal.Length", "Sepal.Width")], col=1:3, pch=23, cex=3)

Method
Explanation

Clusters can be visualized using a scatter plot of at least two variables. Data points are colored according to their cluster assignment, and the cluster centers are plotted as large points.

Conditions
  1. Requires at least two numeric variables for plotting.

  2. Requires cluster assignments and center coordinates from the kmeans output.

Prerequisites
  1. Structure of kmeans output object

kmeans function in R

Clear evidence
Shown in the video
Evidence
  1. Formula
    Observation

    kmeans(iris_data, centers = 3)

Method
Explanation

The kmeans function is used to perform k-means clustering on a dataset. It takes the dataset and the number of centers (clusters) as arguments.

Formula
kmeans(data,centers)kmeans(data, centers)
Conditions
  1. data must be a numeric matrix or data frame

  2. centers must be a positive integer

plot function in R

Clear evidence
Shown in the video
Evidence
  1. Formula
    Observation

    plot(iris_data[c("Sepal.Length", "Sepal.Width")], col=kmeans_iris_result$cluster)

Method
Explanation

The plot function is used to create scatter plots. In this context, it plots the Sepal.Length against Sepal.Width, coloring the points based on their cluster assignment from the k-means result.

Formula
plot(x,y,col)plot(x, y, col)
Conditions
  1. x and y must be numeric vectors of the same length

  2. col can be a vector of colors or integers corresponding to colors

points function in R

Clear evidence
Shown in the video
Evidence
  1. Formula
    Observation

    points(kmeans_iris_result$centers[,c("Sepal.Length", "Sepal.Width")], col=1:3, pch=23, cex=3)

Method
Explanation

The points function adds points to an existing plot. Here, it adds the cluster centers to the scatter plot, using specific colors, point shapes, and sizes.

Formula
points(x,y,col,pch,cex)points(x, y, col, pch, cex)
Conditions
  1. x and y must be numeric vectors

  2. col specifies the color of the points

  3. pch specifies the symbol to be used for the points

  4. cex specifies the size of the points relative to the default size

Worked examples · 1

K-means clustering on the iris dataset

Clear evidence
Shown in the video
Evidence
  1. Audio
    Observation

    Let's use that iris dataset... create a variable... only put the first four columns... partition the data into three clusters... visualize these clusters.

  2. Formula
    Observation

    data(iris) iris_data <- iris[,1:4] set.seed(54321) kmeans_iris_result <- kmeans(iris_data, centers = 3) print(kmeans_iris_result) plot(iris_data[c("Sepal.Length", "Sepal.Width")], col=kmeans_iris_result$cluster) points(kmeans_iris_result$centers[,c("Sepal.Length", "Sepal.Width")], col=1:3, pch=23, cex=3)

Problem

Perform and visualize K-means clustering on the first four columns of the built-in iris dataset, partitioning it into three clusters.

Given
  1. Built-in R dataset: iris

  2. Number of clusters: 3

  3. Variables for plotting: Sepal.Length, Sepal.Width

Goal

Partition the data into three clusters and visualize the resulting clusters and their centers.

Steps
  1. Expression
    data(iris)data(iris)
    Explanation

    Load the built-in iris dataset into the R environment.

    Justification

    Required to access the dataset for analysis.

    Shown in the video
  2. Expression
    irisdata<−iris[,1:4]iris_data <- iris[,1:4]
    Explanation

    Create a new variable containing only the first four columns of the iris dataset.

    Justification

    Simplifies the data for the clustering example.

    Shown in the video
  3. Expression
    set.seed(54321)set.seed(54321)
    Explanation

    Set the random number generator seed.

    Justification

    Ensures reproducibility of the kmeans algorithm results.

    Shown in the video
  4. Expression
    kmeansirisresult<−kmeans(irisdata,centers=3)kmeans_iris_result <- kmeans(iris_data, centers = 3)
    Explanation

    Run the kmeans algorithm on the subsetted data, specifying 3 clusters.

    Justification

    Partitions the data into distinct groups based on the algorithm.

    Shown in the video
  5. Expression
    print(kmeansirisresult)print(kmeans_iris_result)
    Explanation

    Print the resulting kmeans object to the console.

    Justification

    Displays the cluster means and assignments for inspection.

    Shown in the video
  6. Explanation

    Create a scatter plot of Sepal.Length vs Sepal.Width, coloring points by their cluster assignment.

    Justification

    Visualizes the distribution of the data points and their assigned clusters.

    Shown in the video
  7. Explanation

    Add the cluster centers to the existing scatter plot as large, distinctly shaped points.

    Justification

    Highlights the calculated center coordinates for each cluster.

    Shown in the video
Answer

A scatter plot displaying three distinct clusters of data points, with large points marking the center of each cluster.

Verification

The visual output confirms the partitioning of the data into three non-overlapping groups, with centers located within each group.

Visual events · 2

Scatter plot of K-means clusters

Clear evidence
Shown in the video
Evidence
  1. Animation
    Observation

    A scatter plot appears showing data points colored in red, green, and blue, with three large diamond-shaped points representing the cluster centers.

Objects
  1. Data points

  2. Cluster centers

  3. X-axis (Sepal.Length)

  4. Y-axis (Sepal.Width)

Changes
  1. Data points are colored according to their cluster assignment.

  2. Large diamond-shaped points are added to represent the cluster centers.

Invariants
  1. The positions of the data points remain constant once plotted.

  2. The axes scales remain constant.

Interpretation

The plot visually demonstrates the partitioning of the data into three distinct, non-overlapping groups, with the centers representing the mean location of each group.

K-means clustering scatter plot

Clear evidence
Shown in the video
Evidence
  1. Diagram
    Observation

    Scatter plot with colored points representing different clusters and larger diamond-shaped points representing cluster centers.

Objects
  1. Data points

  2. Cluster centers

  3. Axes labels (Sepal.Length, Sepal.Width)

Changes
  1. Points are colored according to their cluster assignment.

  2. Cluster centers are plotted as larger diamond-shaped points.

Invariants
  1. The axes represent Sepal.Length and Sepal.Width.

Interpretation

The scatter plot visualizes the results of the k-means clustering algorithm, showing how the data points are grouped into three distinct clusters based on their sepal dimensions.

Concept relations · 3

Structure of kmeans output object → Visualizing clusters with a scatter plot

Clear evidence
Shown in the video
Evidence
  1. Audio
    Observation

    The speaker explains the output of the kmeans function and then uses that output to create a scatter plot.

Application
Explanation

The cluster assignments and center coordinates extracted from the kmeans output object are directly applied as arguments to the plot and points functions for visualization.

kmeans function in R → plot function in R

Clear evidence
Shown in the video
Evidence
  1. Formula
    Observation

    plot(..., col=kmeans_iris_result$cluster)

Application
Explanation

The output of the kmeans function (specifically the cluster assignments) is used as input to the plot function to visualize the clustering results.

plot function in R → points function in R

Clear evidence
Shown in the video
Evidence
  1. Formula
    Observation

    points(...)

Application
Explanation

The points function is applied to the existing plot created by the plot function to add the cluster centers.

Find an answer · 6

What is the definition of K-means clustering?

Clear evidence
Shown in the video
Evidence
  1. Audio
    Observation

    K-means is a popular clustering algorithm used to partition data into distinct non-overlapping groups.

Knowledge points
  1. Definition of K-means clustering

How do you run K-means clustering in R and specify the number of clusters?

Clear evidence
Shown in the video
Evidence
  1. Formula
    Observation

    kmeans_iris_result <- kmeans(iris_data, centers = 3)

Knowledge points
  1. Using the kmeans function in R

What information is contained in the object returned by the R kmeans function?

Clear evidence
Shown in the video
Evidence
  1. Audio
    Observation

    For each data point, it includes a cluster assignment, and it also includes the coordinate location of the center of the cluster.

Knowledge points
  1. Structure of kmeans output object

How can you visualize K-means clusters and their centers using a scatter plot in R?

Clear evidence
Shown in the video
Evidence
  1. Formula
    Observation

    plot(iris_data[c("Sepal.Length", "Sepal.Width")], col=kmeans_iris_result$cluster)

Knowledge points
  1. Visualizing clusters with a scatter plot

How to perform k-means clustering in R?

Clear evidence
Shown in the video
Evidence
  1. Formula
    Observation

    kmeans(iris_data, centers = 3)

Knowledge points
  1. kmeans function in R

How to visualize k-means clustering results in R?

Clear evidence
Shown in the video
Evidence
  1. Formula
    Observation

    plot(iris_data[c("Sepal.Length", "Sepal.Width")], col=kmeans_iris_result$cluster)

Knowledge points
  1. plot function in R
  2. points function in R
Coverage and review notes

Covered · Introduction to the video and definition of K-means clustering.

Covered · Loading the iris dataset and creating a simplified subset in R.

Covered · Running the kmeans function and examining its output object.

Covered · Visualizing the clusters and their centers using a scatter plot, followed by concluding remarks.

Covered · Introductory remarks and call to action.

Covered · Display of R code for k-means clustering and plotting.

Covered · Outro and logo display.

Explore the knowledge in this video

Reviewed subject paths

Questions this video answers

Find a method

↗
Find a method

↗