Book Image

R Data Analysis Cookbook

By : Viswa Viswanathan, Shanthi Viswanathan
Book Image

R Data Analysis Cookbook

By: Viswa Viswanathan, Shanthi Viswanathan

Overview of this book

<p>Data analytics with R has emerged as a very important focus for organizations of all kinds. R enables even those with only an intuitive grasp of the underlying concepts, without a deep mathematical background, to unleash powerful and detailed examinations of their data.</p> <p>This book empowers you by showing you ways to use R to generate professional analysis reports. It provides examples for various important analysis and machine-learning tasks that you can try out with associated and readily available data. The book also teaches you to quickly adapt the example code for your own needs and save yourself the time needed to construct code from scratch.</p>
Table of Contents (18 chapters)
R Data Analysis Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Performing cluster analysis using K-means clustering


The standard R package stats provides the function for K-means clustering. We also use the cluster package to plot the results of our cluster analysis.

Getting ready

If you have not already downloaded the files for this chapter, do it now and ensure that the auto-mpg.csv file is in your R working directory. Also, ensure that you have installed the cluster package.

How to do it...

To perform cluster analysis using K-means clustering, follow theses steps:

  1. Read the data:

    > auto <- read.csv("auto-mpg.csv")
  2. Define a convenience function to standardize the relevant variables and append the resulting variables to the original data:

    rdacb.scale.many <- function (dat, column_nos) {
      nms <- names(dat)
      for (col in column_nos) {
        name <- paste0(nms[col], "_z")
        dat[name] <- scale(dat[, col])
      }
      cat(paste("Scaled", length(column_nos), "variable(s)\n"))
      dat
    }
  3. Use the preceding convenience function to standardize the variables...