假设 RES 是一个具有 1000 个结构的列表,由函数 kmeans 生成作为输出。
我如何申报RES?
在 RES 声明之后,我想做这样的事情:
for (i in 1:1000) {
RES[i] = kmeans(iris,i)
}
谢谢你。
睿
最佳答案
如果您使用 R 应用习惯用法,您的代码将更简单,您不必提前声明您的变量:
RES <- lapply(1:3, function(i)kmeans(dist(iris[, -5]),i))
结果:
> str(RES)
List of 3
$ :List of 7
..$ cluster : Named int [1:150] 1 1 1 1 1 1 1 1 1 1 ...
.. ..- attr(*, "names")= chr [1:150] "1" "2" "3" "4" ...
..$ centers : num [1, 1:150] 2.89 2.93 3.04 2.96 2.93 ...
.. ..- attr(*, "dimnames")=List of 2
.. .. ..$ : chr "1"
.. .. ..$ : chr [1:150] "1" "2" "3" "4" ...
..$ totss : num 55479
..$ withinss : num 55479
..$ tot.withinss: num 55479
..$ betweenss : num 4.15e-10
..$ size : int 150
..- attr(*, "class")= chr "kmeans"
$ :List of 7
..$ cluster : Named int [1:150] 1 1 1 1 1 1 1 1 1 1 ...
.. ..- attr(*, "names")= chr [1:150] "1" "2" "3" "4" ...
..$ centers : num [1:2, 1:150] 0.531 4.104 0.647 4.109 0.633 ...
.. ..- attr(*, "dimnames")=List of 2
.. .. ..$ : chr [1:2] "1" "2"
.. .. ..$ : chr [1:150] "1" "2" "3" "4" ...
..$ totss : num 55479
..$ withinss : num [1:2] 863 9743
..$ tot.withinss: num 10606
..$ betweenss : num 44873
..$ size : int [1:2] 51 99
..- attr(*, "class")= chr "kmeans"
$ :List of 7
..$ cluster : Named int [1:150] 2 2 2 2 2 2 2 2 2 2 ...
.. ..- attr(*, "names")= chr [1:150] "1" "2" "3" "4" ...
..$ centers : num [1:3, 1:150] 3.464 0.5 5.095 3.438 0.622 ...
.. ..- attr(*, "dimnames")=List of 2
.. .. ..$ : chr [1:3] "1" "2" "3"
.. .. ..$ : chr [1:150] "1" "2" "3" "4" ...
..$ totss : num 55479
..$ withinss : num [1:3] 2593 495 1745
..$ tot.withinss: num 4833
..$ betweenss : num 50646
..$ size : int [1:3] 62 50 38
..- attr(*, "class")= chr "kmeans"
关于list - 如何使用 R 自动创建结构列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7503319/