英文:
How does the function 'Reduce' handle list variables?
问题
我发现了StephaneLaurent在这里对Reduce
的创造性用法。也就是说,在处理列表变量的评论中,他写道
Reduce(`&`, bools)
其中bools
是一个列表变量。
当我查看Reduce
的帮助页面时,它说输入参数x
应该是一个向量。
但是参考的代码将一个列表变量作为输入。
显然,列表变量被视为每个列表中的第一个元素组合成一个向量,然后是每个列表中的第二个元素,依此类推。有人能解释一下Reduce
的“内部”是如何允许这种显然未记录的功能的吗?
英文:
I found a creative use of Reduce
by StephaneLaurent here.
That is, in a comment about handling a list variable, he wrote
Reduce(`&`, bools)
where bools
is a list variable.
When I looked at the help page for Reduce
, it says the input argument x
should be a vector.
But the referenced code feeds a list variable.
Apparently the list variable is treated as though the first element in each list are combined into a vector, then the second in each list, etc. Can someone explain what is going on in the "guts" of Reduce
to allow this apparently undocumented capability?
答案1
得分: 1
如R语言定义中所述:
列表是向量,基本的向量类型被称为原子向量,在需要排除列表时使用。
所以列表是一种向量,因此行为不是未记录的。Reduce会遍历列表,对列表中的每个项目以及上一次迭代的输出应用一个函数。因此,以下两者是相同的:
bools <- list(
c(TRUE, TRUE, TRUE, TRUE),
c(TRUE, TRUE, TRUE, FALSE),
c(TRUE, TRUE, FALSE, TRUE),
c(TRUE, FALSE, TRUE, TRUE)
)
Reduce(`&`, bools)
((bools[[1]] & bools[[2]]) & bools[[3]]) & bools[[4]]
英文:
As stated in the R Language definition
> Lists are vectors, and the basic vector types are referred to as atomic vectors where it is necessary to exclude lists.
So a list is a vector so the behavior isn't undocumented. Reduce will walk the list applying a function to each item in the list along with the output of the previous iteration. So these are the same
bools <- list(
c(TRUE, TRUE, TRUE, TRUE),
c(TRUE, TRUE, TRUE, FALSE),
c(TRUE, TRUE, FALSE, TRUE),
c(TRUE, FALSE, TRUE, TRUE)
)
Reduce(`&`, bools)
((bools[[1]] & bools[[2]]) & bools[[3]]) & bools[[4]]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论