Reduce函数如何处理列表变量?

huangapple go评论57阅读模式
英文:

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 &lt;- list(
  c(TRUE, TRUE, TRUE, TRUE),
  c(TRUE, TRUE, TRUE, FALSE),
  c(TRUE, TRUE, FALSE, TRUE),
  c(TRUE, FALSE, TRUE, TRUE)
)

Reduce(`&amp;`, bools)

((bools[[1]] &amp; bools[[2]]) &amp; bools[[3]]) &amp; bools[[4]]

huangapple
  • 本文由 发表于 2023年6月16日 04:08:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76485190.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定