Understanding reduce function

A nice way to see what Reduce() is doing is to run it with its argument accumulate=TRUE. When accumulate=TRUE, it will return a vector or list in which each element shows its state after processing the first n elements of the list in x. Here are a couple of examples:

list第一项和第二项通过指定的函数或运算变成一项,再与第三期项通过指定的函数或运算变成下一项,如此类推,与apply 或dplyr::map不太一样,后者是将指定函数应用于list的每项上

Reduce(`*`, x=list(5,4,3,2), accumulate=TRUE)

# [1]  5  20  60 120

i2 <- seq(0,100,by=2)

i3 <- seq(0,100,by=3)

i5 <- seq(0,100,by=5)

Reduce(intersect, x=list(i2,i3,i5), accumulate=TRUE)

# [[1]]

#  [1]  0  2  4  6  8  10  12  14  16  18  20  22  24  26  28  30  32  34  36

# [20]  38  40  42  44  46  48  50  52  54  56  58  60  62  64  66  68  70  72  74

# [39]  76  78  80  82  84  86  88  90  92  94  96  98 100

#

# [[2]]

#  [1]  0  6 12 18 24 30 36 42 48 54 60 66 72 78 84 90 96

#

# [[3]]

# [1]  0 30 60 90

你可能感兴趣的:(Understanding reduce function)