Skip to content
← All questions

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

You run K-means clustering in R using the kmeans() function. You pass the dataset as the first argument and specify the number of clusters using the centers argument, for example, centers = 3.

Conditions

  • Requires a numeric dataset.
  • Requires specifying the number of clusters (centers).

Reasoning, step by step

  1. Load the dataset into R.
  2. Call the kmeans() function.
  3. Pass the data as the first argument.
  4. Set the centers argument to the desired number of clusters.
  5. Store the result in a variable.

Example

The video shows the code: kmeans_iris_result <- kmeans(iris_data, centers = 3), which partitions the iris_data into three clusters.

Common misconceptions

  • Forgetting to set the centers argument.
  • Assuming the kmeans function returns only the cluster assignments without the centers.

Watch the explanation

Explore next

Answers are generated from source material and independently checked. Consult the original video or creator if something is unclear.