Home
/
Blog
/
Developer Insights
/
Practical Guide to Clustering Algorithms and Evaluation in R

Practical Guide to Clustering Algorithms and Evaluation in R

Author
Manish Saraswat
Calendar Icon
January 19, 2017
Timer Icon
3 min read
Share

Explore this post with:

Introduction

Clustering algorithms are a part of unsupervised machine learning algorithms. As there is no target variable, the model is trained using input variables to discover intrinsic groups or clusters.

Because we don’t have labels for the data, these groups are formed based on similarity between data points. This tutorial covers clustering concepts, techniques, and applications across domains like healthcare, retail, and manufacturing.

We’ll also walk through examples in R, using real-world data from a water treatment plant to apply our knowledge practically.

Table of Contents

  1. Types of Clustering Techniques
  2. Distance Calculation for Clustering
  3. K-Means Clustering
  4. Choosing the Best K in K-Means
  5. Hierarchical Clustering
  6. Evaluation Methods in Cluster Analysis
  7. Clustering in R – Water Treatment Plants

Types of Clustering Techniques

Common clustering algorithms include K-Means, Fuzzy C-Means, and Hierarchical Clustering. Depending on the data type (numeric, categorical, mixed), the algorithm may vary. Clustering techniques can be classified as:

  • Soft Clustering – Observations are assigned to clusters with probabilities.
  • Hard Clustering – Observations belong to only one cluster.

We’ll focus on K-Means and Hierarchical Clustering in this guide.

Distance Calculation for Clustering

Distance metrics are used to measure similarity between data points. Common metrics include:

  • Euclidean Distance – Suitable for numeric variables.
  • Manhattan Distance – Measures horizontal and vertical distances.
  • Hamming Distance – Used for categorical variables.
  • Gower Distance – Handles mixed variable types.
  • Cosine Similarity – Common in text analysis.

K-Means Clustering

K-Means partitions data into k non-overlapping clusters. The process includes:

  1. Randomly assign k centroids.
  2. Assign observations to the nearest centroid.
  3. Recalculate centroids.
  4. Repeat until convergence.

Clustering minimizes within-cluster variation using squared Euclidean distance.

Choosing the Best K in K-Means

Methods for selecting k include:

  • Cross Validation
  • Elbow Method
  • Silhouette Method
  • X-Means Clustering

Hierarchical Clustering

This method creates a nested sequence of clusters using two approaches:

  • Agglomerative – Bottom-up merging.
  • Divisive – Top-down splitting.

Dendrograms visualize the clustering hierarchy. A horizontal cut across the dendrogram reveals the number of clusters.

Evaluation Methods

Clustering evaluation is divided into:

  • Internal Measures – Based on compactness and separation (e.g., SSE, Scatter Criteria).
  • External Measures – Based on known labels (e.g., Rand Index, Precision-Recall).

Clustering in R – Water Treatment Plants

The water treatment dataset from the UCI repository is used to demonstrate hierarchical and k-means clustering.

# Load and preprocess data
library(data.table)
library(ggplot2)
library(fpc)

water_data <- read.table("water-treatment.data.txt", sep = ",", header = F, na.strings = "?")
setDT(water_data)

# Impute missing values
for(i in colnames(water_data)[-1]) {
  set(water_data, which(is.na(water_data[[i]])), i, median(water_data[[i]], na.rm = TRUE))
}

# Scale numeric features
scaled_wd <- scale(water_data[,-1, with = FALSE])

Next, hierarchical clustering is performed using Euclidean distance and Ward's method. A dendrogram is plotted, and clusters are determined via horizontal cuts. PCA is used to visualize clusters.

# Hierarchical clustering
d <- dist(scaled_wd, method = "euclidean")
h_clust <- hclust(d, method = "ward.D2")
plot(h_clust, labels = water_data$V1)

# Cut dendrogram
rect.hclust(h_clust, k = 4)
groups <- cutree(h_clust, k = 4)

Principal components are used for cluster visualization:

# PCA for visualization
pcmp <- princomp(scaled_wd)
pred_pc <- predict(pcmp)[,1:2]
comp_dt <- cbind(as.data.table(pred_pc), cluster = as.factor(groups), Labels = water_data$V1)

ggplot(comp_dt, aes(Comp.1, Comp.2)) +
  geom_point(aes(color = cluster), size = 3)

Then, k-means clustering is applied and similarly visualized using PCA components. The clustering consistency is confirmed visually.

# K-means clustering
kclust <- kmeans(scaled_wd, centers = 4, iter.max = 100)

ggplot(comp_dt, aes(Comp.1, Comp.2)) +
  geom_point(aes(color = as.factor(kclust$cluster)), size = 3)

Subscribe to The HackerEarth Blog

Get expert tips, hacks, and how-tos from the world of tech recruiting to stay on top of your hiring!

Author
Manish Saraswat
Calendar Icon
January 19, 2017
Timer Icon
3 min read
Share

Hire top tech talent with our recruitment platform

Access Free Demo
Related reads

Discover more articles

Gain insights to optimize your developer recruitment process.

What Gen Z Expects From HR Leaders in 2026

What Gen Z Expects From HR Leaders in 2026

Introduction

Gen Z is entering the workforce with a very different perspective on work, leadership, and career growth.

Unlike previous generations, they are not just evaluating salary packages or job titles. They are paying closer attention to workplace culture, flexibility, transparency, learning opportunities, and overall employee experience.

For HR and Talent Acquisition leaders, this shift is changing how organizations attract, engage, and retain talent.

Having entered the workforce during a period of rapid workplace transformation, Gen Z values authenticity over polished corporate messaging and meaningful experiences over traditional corporate structures.

Employer Branding Is Now About Experience

Employer branding today is no longer defined only by career pages or company values.

Gen Z pays attention to how recruiters communicate, how transparent the hiring process feels, and how employees speak about the company publicly.

For Talent Acquisition teams, recruitment is no longer just a hiring function. It has become a reflection of workplace culture itself.

Candidates today value clear communication, transparency, honest conversations around growth, and personalized experiences throughout the hiring journey.

This is also why skill-based hiring and fair evaluation processes are becoming more important for modern organizations.

Gen Z Values Authenticity

One of the biggest shifts HR leaders are noticing is that Gen Z values honesty far more than polished corporate narratives.

They want realistic conversations around career growth, workplace expectations, compensation, and learning opportunities.

Interestingly, they do not expect organizations to be perfect. What they expect is transparency and authenticity.

Younger employees quickly recognize when workplace messaging feels disconnected from reality. Organizations that communicate openly tend to build stronger trust and credibility with Gen Z talent.

Career Growth Looks Different Today

Traditional career growth models were designed around long timelines and annual reviews.

But Gen Z expects growth to feel continuous.

Instead of waiting for yearly discussions, employees want faster feedback, ongoing learning, mentorship opportunities, and clear visibility into growth from the beginning of their journey.

This means career development is no longer just part of appraisal cycles. It is becoming an everyday part of the employee experience.

Organizations investing in learning, internal mobility, and skill development are more likely to keep younger employees engaged.

Flexibility Is About Trust

For Gen Z, flexibility is no longer viewed as a workplace perk.

It is an expectation.

But flexibility goes beyond remote or hybrid work. It also includes autonomy in how employees manage work and productivity.

At its core, flexibility has become a question of trust.

Gen Z values workplaces where managers focus on outcomes instead of constant visibility or monitoring. For HR leaders, this means flexibility cannot exist only in policies. It must also exist in leadership behavior and workplace culture.

Well-Being Is Part of the Work Experience

For Gen Z employees, mental well-being is not a separate HR initiative.

It is part of the everyday employee experience.

They are quick to notice the gap between organizations talking about wellness and employees actually feeling supported.

This means HR teams need to think beyond wellness campaigns and focus more on how work itself is designed and managed.

Because employees do not experience policies. They experience culture every single day.

Final Thoughts

Gen Z is not simply changing workplace expectations. They are challenging organizations to rethink how modern work should actually function.

For HR and Talent Acquisition leaders, this creates an opportunity to build more transparent, flexible, and people-focused workplaces.

The organizations that will attract and retain Gen Z talent successfully are not necessarily the ones with the loudest employer branding or trendiest benefits.

They are the ones building cultures based on trust, authenticity, flexibility, growth, and meaningful employee experiences.

Remote, Hybrid, or Office? What Actually Works and Why

Remote vs Hybrid vs Office: What Actually Works in 2026?

Introduction

Somewhere between “you’re on mute” and badge-swiping back into office buildings, work didn’t just change, it split into choices.

Remote work. Hybrid work. Office-first culture.

Policies were rewritten again and again, but one question still dominates HR and Talent Acquisition conversations:

Are organizations building work models that genuinely improve productivity, employee experience, and retention, or simply reacting to pressure from leadership, candidates, and competitors?

The truth is, there’s no universal answer.

The Myth of the Perfect Work Model

Over the last few years, companies have learned that no single workplace model works for everyone.

Organizations that embraced fully remote work gained access to wider talent pools and improved flexibility. But many also struggled with collaboration gaps, communication fatigue, and weaker cultural connection.

Meanwhile, strict return-to-office policies brought structure and in-person collaboration back, but often at the cost of employee satisfaction and retention.

Hybrid work quickly became the middle ground. Yet in practice, hybrid is often the hardest model to execute well because it demands balance, consistency, and intentional leadership.

The real question isn’t whether remote, hybrid, or office is better.

It’s: What outcome is the organization trying to optimize for?

What HR Leaders Are Seeing

HR teams across industries are noticing a shift in how people work and what employees value.

Remote hiring has dramatically expanded access to talent beyond geographical boundaries. Talent Acquisition teams can now hire specialized talent faster and from more diverse locations.

At the same time, office environments still play an important role in onboarding, mentorship, and early-career learning. Informal conversations, quick collaboration, and day-to-day exposure are still difficult to replicate virtually.

Hybrid models try to combine both advantages, but they also introduce challenges like proximity bias, where employees who spend more time in the office often receive greater visibility and growth opportunities.

This raises an important question for HR leaders:

Are workplace policies rewarding performance or simply physical presence?

What Candidates Actually Want

Candidates today are not just choosing jobs anymore. They’re choosing lifestyles.

For many professionals, remote work represents flexibility, autonomy, and better work-life balance. For others, especially younger professionals, office environments provide structure, mentorship, and stronger human connection.

What’s interesting is that candidate preferences are becoming more nuanced.

Someone may prefer remote work but still choose a hybrid role if it offers stronger career growth. Another candidate may prioritize flexibility over compensation altogether.

For Talent Acquisition teams, this changes everything.

Work models are no longer just operational policies. They’ve become part of the employer value proposition.

Culture Is More Than a Workplace

There’s a common belief that culture only exists inside offices.

But culture isn’t tied to a physical location. It’s shaped through communication, trust, leadership, and shared experiences.

Organizations that succeed with remote work usually focus on clear communication, strong documentation, and outcome-based performance management rather than constant visibility.

Meanwhile, companies succeeding with office-first models are redefining what offices are actually meant for: collaboration, creativity, and connection instead of simply showing up at a desk.

Because if employees are commuting only to spend the day on virtual meetings, the office experience loses its purpose.

What Actually Works?

The organizations getting workplace strategy right are not obsessing over whether remote, hybrid, or office is superior.

Instead, they are focusing on intentionality.

They listen closely to employee behavior and outcomes, not just survey responses. They treat work models as evolving systems instead of fixed policies. Most importantly, they align workplace strategy with business goals and employee needs simultaneously.

That’s where the real difference lies.

Final Thoughts

The future of work isn’t remote, hybrid, or office-first.

It’s intentional, adaptable, and human-centered.

The companies that understand this won’t just attract better talent, they’ll build stronger cultures, healthier teams, and more sustainable workplaces for the future.

5 Habits That Make You Stand Out at Work

5 Habits That Make You Stand Out at Work

Standing out at work is not always about doing more. In many cases, professional success comes down to how you think, communicate, and respond under pressure.

Employees who consistently stand out in the workplace are often the ones who remain calm in difficult situations, communicate with clarity, and bring thoughtful input into conversations. These workplace habits build trust, improve leadership presence, and create long-term career growth opportunities.

The good news is that these are not natural talents reserved for a few professionals. They are habits that can be practiced, improved, and strengthened over time.

For professionals looking to improve workplace communication skills, leadership qualities, and career development, the following habits can make a significant difference.

1. Pause Before You React

One of the most important professional habits is learning how to respond calmly instead of reacting instantly.

When something goes wrong at work, the natural instinct is often to answer immediately. However, fast reactions do not always lead to effective communication or strong decision-making.

Taking a moment to:

  • Understand the situation
  • Gather context
  • Process information carefully
  • Think through your response

can help professionals communicate more clearly and avoid unnecessary confusion.

In high-pressure workplace environments, calm responses often leave a stronger impression than rushed reactions.

Professionals who stay composed during stressful moments are frequently seen as more reliable, emotionally intelligent, and leadership-ready.

2. Give Yourself Time to Think

Not every workplace question requires an instant answer.

Saying:

“Let me think about that.”

can actually make you sound more confident and thoughtful.

This simple communication habit shows that you value clarity and accuracy instead of speaking just to fill silence.

In:

  • Team meetings
  • Leadership discussions
  • Job interviews
  • Client conversations
  • Stakeholder presentations

taking time to think can improve both the quality of your response and the way people perceive your judgment.

Strong professionals are often recognized not for how quickly they respond, but for how thoughtfully they process information and communicate ideas.

This is a critical workplace communication skill that improves professional credibility over time.

3. Get Comfortable With Silence

Silence makes many people uncomfortable.

As a result, professionals often rush to fill every pause during meetings, interviews, or conversations.

But silence can actually improve communication effectiveness.

A short pause gives you time to:

  • Organize your thoughts
  • Deliver stronger responses
  • Improve clarity
  • Communicate with more intention
  • Reduce unnecessary overexplaining

Professionals who are comfortable with silence often appear:

  • More composed
  • More self-assured
  • More confident under pressure
  • Better at executive communication

especially in high-stakes professional situations.

Learning how to stay calm during silence is an underrated but valuable professional development skill.

4. Ask One Thoughtful Question

You do not need to speak the most to stand out at work.

Sometimes, one thoughtful question creates more impact than a long explanation.

Thoughtful questions can:

  • Reveal blind spots
  • Improve team discussions
  • Encourage strategic thinking
  • Demonstrate leadership potential
  • Show strong critical thinking skills

Employees who ask meaningful questions are often viewed as more engaged, analytical, and solution-oriented.

This is one of the fastest ways to leave a memorable impression in workplace conversations and professional meetings.

Strong leaders are not only recognized for giving answers.

They are also recognized for asking the right questions.

5. Keep Your Communication Clear and Concise

One of the most valuable workplace skills is clear and concise communication.

Overexplaining can weaken even strong ideas.

Professionals who stand out in the workplace are often the ones who communicate with structure, simplicity, and clarity.

They focus on:

  • What matters
  • Why it matters
  • What action is needed

without adding unnecessary complexity.

Clear communication improves:

  • Workplace collaboration
  • Leadership presence
  • Team alignment
  • Professional confidence
  • Decision-making conversations

In modern workplaces, communication skills are often just as important as technical expertise.

The ability to explain ideas clearly is a major differentiator for career growth and leadership development.

Why These Workplace Habits Matter

These habits sound simple, but they become difficult to apply when the pressure is real.

In:

  • Job interviews
  • High-pressure meetings
  • Leadership conversations
  • Workplace conflict situations
  • Client presentations

people often rush, overtalk, or respond before fully thinking through the situation.

That is why practice matters.

Professional communication skills improve through repetition, structured feedback, and realistic practice environments.

Employees who consistently practice these habits often become more confident communicators and stronger workplace contributors over time.

Practice Before the Pressure Is Real

If you want to improve how you think and communicate under pressure, you need opportunities to practice those moments before they actually matter.

HackerEarth OnScreen (AI Interviewer) helps professionals build workplace communication skills, interview confidence, and structured thinking through realistic AI-led interview experiences.

The platform helps professionals:

  • Practice answering questions clearly
  • Improve communication under pressure
  • Structure thoughts effectively
  • Build interview confidence
  • Develop executive communication skills
  • Get comfortable with pauses and silence
  • Improve professional speaking habits

It is not only designed for interview preparation.

It also helps professionals strengthen the workplace habits that improve career growth, leadership readiness, and communication confidence.

👉 Try HackerEarth OnScreen and practice the habits that help you stand out when it matters most.

Final Thought

Standing out at work is not about being the loudest person in the room.

It is about being:

  • Thoughtful
  • Clear
  • Calm under pressure
  • Confident in communication
  • Intentional in your responses

Professionals who consistently develop these habits often build stronger workplace relationships, better leadership presence, and long-term career success.

And the more you practice these habits, the more naturally they appear in the moments that shape your professional growth and career opportunities.

Top Products

Explore HackerEarth’s top products for Hiring & Innovation

Discover powerful tools designed to streamline hiring, assess talent efficiently, and run seamless hackathons. Explore HackerEarth’s top products that help businesses innovate and grow.
Frame
Hackathons
Engage global developers through innovation
Arrow
Frame 2
Assessments
AI-driven advanced coding assessments
Arrow
Frame 3
FaceCode
Real-time code editor for effective coding interviews
Arrow
Frame 4
L & D
Tailored learning paths for continuous assessments
Arrow
Get A Free Demo