我有以下代码:
for (i in 1:5) {
print(i)
iris_cluster[i]<- kmeans(iris_data[1:4], i, nstart = 10)
}
kmeans() is this: https://www.rdocumentation.org/packages/stats/versions/3.6.2/topics/kmeans
但是运行它时出现以下错误:
Error in `[<-.data.frame`(`*tmp*`, i, value = list(cluster = c(`1` = 1L, : replacement element 2 is a matrix/data frame of 1 row, need 150
我正在使用r随附的著名的Iris数据集。
我正在寻找创建五个数据框:
iris_cluster1
iris_cluster2
iris_cluster3
iris_cluster4
iris_cluster5
If the dataset is 'iris', we create a
list
withlapply
and use
list2env
if we need separate objects in the global env (not recommended)If we check the
str
ucture of the output of one of the elements, it is a namedlist
of either vector ormatrix
. Thelist
elements can be extracted with$
or[[
从一个元素中,“ withinss”可以提取为
From the
list
, we can loop over thelist
withlapply/sapply
. As thelength
is different, eitherunlist
orstack
it to two-columndata.frame
to return the cluster name as well. From here, we can extract the 'values' with either$
or[[