繁体   English   中英

如何使用R自动创建结构列表?

[英]How can I create a list of structures automatically with R?

让我们说RES是一个容量为1000个结构的列表,其功能kmeans生成为输出。

我如何申报RES?

在RES声明后我想做这样的事情:

for (i in 1:1000) {
  RES[i] = kmeans(iris,i)
}

谢谢。

如果你使用R apply idiom,你的代码会更简单,你不必提前声明你的变量:

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"

在这种情况下,我认为lapply是正确的答案。 但是有许多场景需要循环,这是一个很好的问题。

R列表不需要提前声明为空,因此最简单的方法是将' RES '声明为空列表:

RES <- list()
for (i in 1:1000) {
   RES[i] = kmeans(iris,i)
}

R只会扩展每次迭代的列表。

顺便提一下,这甚至适用于非顺序索引:

newList <- list()
newList[5] <- 100

产生一个列表,其中插槽1到4设计为NULL,第五个插槽中的数字为100。

这一切只是说,名单中的R比原子向量非常不同的东西。

遗憾的是,创建列表的方法与创建数字向量的常用方法不同。

# The "usual" way to create a numeric vector
myNumVec <- numeric(1000) # A numeric vector with 1000 zeroes...

# ...But there is also this way
myNumVec <- vector("numeric", 1000) # A numeric vector with 1000 zeroes...


# ...and that's the only way to create lists:

# Create a list with 1000 NULLs
RES <- vector("list", 1000)

所以你的榜样会变成,

RES <- vector("list", 1000)
for (i in 1:1000) {
  RES[[i]] = kmeans(iris,i) 
}

(请注意,kmeans不喜欢直接调用iris数据集,但是......)

但是再一次, lapply也会这样做,并且以@Andrie表现的更直接的方式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM