如何使用 R 自动创建结构列表?
假设 RES 是一个容量为 1000 个结构的列表,由函数 kmeans 生成作为输出。
如何声明 RES?
声明 RES 后,我想做这样的事情:
for (i in 1:1000) {
RES[i] = kmeans(iris,i)
}
谢谢。 锐
Lets say that RES is a list with capacity for 1000 structs that function kmeans generates as output.
How do I declare RES?
After having RES declared I want to do something like this:
for (i in 1:1000) {
RES[i] = kmeans(iris,i)
}
Thank you.
Rui
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您使用 R apply 习惯用法,您的代码会更简单,并且不必提前声明变量:
结果:
If you use the R apply idiom, your code will be simpler and you don't have to declare your variable in advance:
The results:
我同意在这种情况下
lapply
是正确的答案。但有很多场景需要循环,这是一个很好的问题。
R 列表不需要提前声明为空,因此最简单的方法是将
RES
'声明'为空列表:R 只会为每次迭代扩展列表。
顺便说一句,这甚至适用于非顺序索引:
生成一个列表,其中插槽 1 到 4 设计为 NULL,第五个插槽中的数字 100。
这只是说 R 中的列表与原子向量非常不同。
I'll second that
lapply
is the right answer in this case.But there are many scenarios where a loop is necessary, and it's a good question.
R lists don't need to be declared as empty ahead of time, so the easiest way to do this would to just 'declare'
RES
as an empty list:R will just extend the list for each iteration.
Incidentally, this works even for non-sequential indexing:
yields a list with slots 1 through 4 designed as NULL and the number 100 in the fifth slot.
This is all just to say that lists are very different beasts in R than the atomic vectors.
不幸的是,创建列表的方法与创建数值向量的通常方法不同。
所以你的例子会变成,
(请注意,kmeans 不喜欢像那样直接用 iris 数据集调用......)
但是,
lapply
也会这样做,并且以更多的方式正如@Andrie 所示的直接方式。The way to create a list is unfortunately different from the usual way of creating a numeric vector.
So your example would become,
(Note that kmeans doesn't like to be called with the iris data set directly like that though...)
But then again,
lapply
would do it too and in a more direct way as @Andrie showed.