O'Reilly logo

R Data Analysis Cookbook - Second Edition by Kuntal Ganguly

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

To perform cluster analysis using kmeans clustering, follow these steps:

  1. First, load the protein.csv file and do some preprocessing to add row names as Country name and remove the Country variable before normalizing the data:

> proteinIntake <- read.csv("protein.csv")> rownames(proteinIntake)=proteinIntake$Country> proteinIntake$Country=NULL> proteinIntakeScaled = as.data.frame(scale(proteinIntake))
  1. Now use kmeans to cluster the scaled protein intake data:
> set.seed(22) ## To fix the random cluster initialization> kmFit = kmeans(proteinIntakeScaled, 4)> kmFit

Here is the K-means clustering indicative of the code:

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required