r语言kmeans聚类代码
时间: 2023-09-25 15:07:06 浏览: 52
Sure! Here's an example code for performing k-means clustering in R:
```R
# Load the required package
library(stats)
# Generate some random data
set.seed(123)
data <- matrix(rnorm(1000), ncol = 2)
# Perform k-means clustering
k <- 3 # Number of clusters
kmeans_result <- kmeans(data, centers = k)
# Get the cluster assignments for each data point
cluster_assignment <- kmeans_result$cluster
# Print the cluster centroids
cluster_centroids <- kmeans_result$centers
print(cluster_centroids)
# Plot the clusters
plot(data, col = cluster_assignment, pch = 16)
points(cluster_centroids, col = 1:k, pch = 3, cex = 2)
```
In this example, we first load the `stats` package, which provides the `kmeans()` function. We then generate some random data with 2 dimensions. Next, we perform k-means clustering by calling `kmeans()` and specifying the number of clusters (`k`) and the data (`data`). The result is stored in `kmeans_result`. We can extract the cluster assignments for each data point using `kmeans_result$cluster`. The cluster centroids are stored in `kmeans_result$centers`. Finally, we plot the data points with different colors corresponding to their cluster assignments and mark the cluster centroids with larger symbols.