You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言K-means聚类组内方差绘图报错:'x'与'y'长度不一致问题咨询

Fixing the 'x' and 'y' Lengths Differ Error in K-means Within-SS Plot

Let’s break down why you’re hitting this error and how to fix it quickly.

The Root Cause

When you initialize w <- numeric(20), you create a vector of length 20 (indices 1 to 20). But your loop only assigns values to w[2] through w[20] (since k runs from 2 to 20), leaving w[1] as an unassigned NA.

When you try to plot 2:20 (which has 19 elements) against w (which has 20 elements), R throws the "lengths differ" error because it can’t pair each x-value with a corresponding y-value one-to-one.

Two Simple Fixes

Option 1: Adjust the vector length to match your K range

Initialize w to be exactly the length of your target K values (19 elements for K=2 to 20), then map your loop index to the correct K value:

# Initialize vector for 19 values (K=2 to 20)
w <- numeric(19)
for (i in 1:19) {
  k <- i + 1  # Shift index to get K from 2 to 20
  kf <- kmeans(whs2018annexBdatscl, k, nstart=100)
  w[i] <- kf$tot.withinss
}
# Now x and y are both length 19
plot(2:20, w, type = "b", lwd=2, pch=19, xlab="K", ylab = expression(SS[within]))

Option 2: Slice the w vector to match your x range

Keep your original loop, but when plotting, only use the elements of w that correspond to K=2 to 20 (i.e., w[2:20]):

w <- numeric(20)
for (k in 2:20) {
  kf <- kmeans(whs2018annexBdatscl,k,nstart=100)
  w[k] <- kf$tot.withinss
}
# Select only the relevant part of w to match x's length
plot(2:20, w[2:20], type = "b", lwd=2, pch=19, xlab="K", ylab = expression(SS[within]))

Why plotting 1:20 worked (but isn’t ideal)

When you plot 1:20 against w, both vectors are length 20. R just ignores the NA value at w[1] and plots the rest—but this includes an unwanted K=1 point (which you don’t need) and hides the actual length mismatch issue.

Either of the fixes above will give you the clean plot of K=2 to 20 that you’re looking for.

内容的提问来源于stack exchange,提问作者JR0428

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 13:27:32